这是我到目前为止制作的代码。我有两个词,红色和黑色。当按下红色按钮时,我想要一个 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"
}
}
你的代码有一些问题...
您不想将字符串传递到Int
初始值设定项中,否则会得到nil
:
Int("Red") // don't do this
接下来,无论如何,您都会匹配整个数组,这也不起作用:
if array == Int("Red") // will never == true
您希望根据打印语句中的内容进行匹配:
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"
}
}