且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过数字范围随机化

更新时间:2023-02-23 12:54:31

我不太确定为什么您的代码是

I´m not quite sure why your code is not working, but try this code instead this works.

var usedNumbers = [Int]()
var randomConv = 0

@IBAction func btnRandomPressed(sender: AnyObject) {
     randomConv = Int(arc4random_uniform(12) + 1)

        if usedNumbers.contains(randomConv) {
            // If you find a duplicate you fire the event again and a new number will be randomized
            print("Exists \(randomConv)")
            btn_Pressed.sendActionsForControlEvents(.TouchUpInside)

        } else {
            print(randomConv)
            lblTest.text = String(randomConv)
            usedNumbers.append(randomConv)

       }
}

更新

usedNumbers.contains(randomConv)条件为 true ,您可以使用此行来触发再次执行按钮事件: btn_Pressed.sendActionsForControlEvents(.TouchUpInside)-btn_Pressed是您的故事板中的按钮出口。

Update
When the usedNumbers.contains(randomConv) condition is true, you can use this row to fire the button event again: btn_Pressed.sendActionsForControlEvents(.TouchUpInside) - btn_Pressed is your buttons outlet from your Storyboard.

我已经更新了代码块,以便您可以看到完整的示例。

I have updated the code block so that you can see a fully working example.

更新2,替代解决方案

func randomize(){
    repeat {
        if (usedNumbers.count == 12){
            return
        }
        randomConv = Int(arc4random_uniform(12) + 1)
    } while usedNumbers.contains(randomConv)

    usedNumbers.append(randomConv)
    lblTest.text = String(randomConv)
}

@IBAction func btnRandomPressed(sender: AnyObject) {
     randomize()
}