gpt4 book ai didi

ios - 我在 Swift 中的 if 语句无法正常工作

转载 作者:行者123 更新时间:2023-11-30 11:58:41 25 4
gpt4 key购买 nike

谁能告诉我我的代码有什么问题吗?我打印了随机数,以便我可以看到它,但即使数字为零并且我按下左按钮,它仍然告诉我错误。但它只是有时这样做。有谁知道出了什么问题吗?我正在使用 Swift 编写。

import UIKit

ViewController 类:UIViewController {

@IBOutlet weak var TopLabel: UILabel!

@IBOutlet weak var LeftImageView: UIImageView!
@IBOutlet weak var RightImageView: UIImageView!
var randomNUmber = arc4random_uniform(2)


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ChosePictures()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}




@IBAction func Next(_ sender: Any) {
ChosePictures()
randomNUmber = arc4random_uniform(2)
}



func ChosePictures() {

print(randomNUmber)
var PictureArrayOne = ["dog", "mushroom", "schedule", "cat"]
var PictureArrayTwo = ["shower", "chess", "food"]

let PickedPictureOne = PictureArrayOne[Int(arc4random_uniform(4))]

let PickedPictureTwo = PictureArrayTwo[Int(arc4random_uniform(3))]

let PickedPictures = [PickedPictureOne, PickedPictureTwo]
LeftImageView.image = UIImage(named: PickedPictures[0])
RightImageView.image = UIImage(named: PickedPictures[1])

TopLabel.text = PickedPictures[Int(randomNUmber)]

}


@IBAction func LeftButton(_ sender: Any) {
if randomNUmber == 0{
TopLabel.text = "Right!"
}else{
TopLabel.text = "Wrong"
}

}





@IBAction func RightButton(_ sender: Any) {
if randomNUmber == 1{
TopLabel.text = "Right!"
}else{
TopLabel.text = "wrong"
}


}

}

最佳答案

您仅加载 arc4random 一次。

@IBOutlet weak var TopLabel: UILabel!

@IBAction func LeftButton(_ sender: Any) {
let randomNumberResults = arc4random_uniform(2)
print(randomNumberResults)
if randomNumberResults == 0 {
TopLabel.text = "Right!"
} else {
TopLabel.text = "Wrong"
}
}



@IBAction func RightButton(_ sender: Any) {
let randomNumberResults = arc4random_uniform(2)
print(randomNumberResults)
if randomNumberResults == 1 {
TopLabel.text = "Right!"
} else {
TopLabel.text = "Wrong"
}

}

你可以这样做并使用按钮重新加载 arc4

var randomNumberResults = Int32()


@IBOutlet weak var TopLabel: UILabel!

@IBAction func arc4(_ sender: Any) {
randomNumberResults = Int32(arc4random_uniform(2))
}

@IBAction func LeftButton(_ sender: Any) {
print(randomNumberResults)
if randomNumberResults == 0 {
TopLabel.text = "Right!"
} else {
TopLabel.text = "Wrong"
}
}



@IBAction func RightButton(_ sender: Any) {
print(randomNumberResults)
if randomNumberResults == 1 {
TopLabel.text = "Right!"
} else {
TopLabel.text = "Wrong"
}

}

关于ios - 我在 Swift 中的 if 语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47497857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com