如果语句调用随机数组

时间:2016-02-29 01:20:25

标签: arrays swift if-statement

这是我到目前为止所做的代码。我有两个字,红色和黑色。当按下红色按钮时,我想要一个if语句,告诉用户他们是错还是错。代码随机选择红色或黑色,但我似乎无法想象如何将if语句与随机选择的单词匹配。

@IBAction func red(sender: AnyObject) {

    let array = ["Red", "Black"]
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    print(array[randomIndex])


    if array == Int("Red") {

        colorLabel.text = "You're right"


    } else {

        colorLabel.text = "Wrong! It was a Black"
    }



}

1 个答案:

答案 0 :(得分:3)

您的代码存在一些问题......

您不希望将字符串传递到Int初始值设定项,或者您将获得nil

 Int("Red") // don't do this

接下来,无论如何,你在整个阵列上都是匹配的,这也是无效的:

if array == Int("Red") // will never == true

您希望根据print语句中的内容进行匹配:

var word = array[randomIndex] // set up a new variable

解决方案

你想要尝试更像这样的东西:

@IBAction func red(sender: AnyObject) {
    let array = ["Red", "Black"]
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    var word = array[randomIndex]

    if word == "Red" {
        colorLabel.text = "You're right"
    } else {  
       colorLabel.text = "Wrong! It was a Black"
    }
}