gpt4 book ai didi

ios - Xcode 中的流控制

转载 作者:行者123 更新时间:2023-11-29 01:46:25 25 4
gpt4 key购买 nike

出于某种原因,即使输入了一个有效输入,即一个整数,它似乎确实进入了函数中的 if 语句,@IBAction func guess(sender: UIButton){}。换句话说,如果我输入 5,控制台输出将显示“请输入有效数字”。不是“你猜高了”或“你猜低了”或“你赢了!”。关于如何解决这个问题有什么建议吗?

以下是我的代码:

class ViewController: UIViewController {

//just some member variables. I don't think the problem is here.
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var output: UITextView!
var guesses : UInt = 0;
var number : UInt32 = 0;
var gameover = false;
let MAX_GUESSES = 8;
var possibleGuess : Int?

override func viewDidLoad() {
super.viewDidLoad()
number = generateNewNumber()
consoleOut("I'm thinking of a number...\n")
var possibleGuess : Int? = inputField.text.toInt()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//consoleOut here prints out stuff on the app.
func consoleOut(text : String) {
output.text = output.text + text;
}

func generateNewNumber() -> UInt32 {
return arc4random_uniform(100) + 1
}

func clearInput() {
output.text = ""
}

//here lies the problem. The control never seems to go inside of
//if let guess = possibleGuess{}
@IBAction func guess(sender: UIButton) {
if let guess = possibleGuess {
if UInt32(guess) > number {
consoleOut("\(guess): You guessed to high\n")
++guesses
}
else if UInt32(guess) < number {
consoleOut("\(guess): You guessed to low\n")
++guesses
}
else {
consoleOut("\(guess): You win!\n")
consoleOut("Go again? (y/n)")
guesses = 0
gameover = true
}
clearInput()
}
else {
clearInput()
consoleOut("Please input a valid number")
}
}
}

最佳答案

这是一个很常见的错误。

您将变量 possibleGuess 声明为可选的 Int 实例变量,但稍后您在 viewDidLoad() 中声明了一个同名变量,其作用域仅限于 viewDidLoad() 方法内。

解决方案:删除viewDidLoad()方法中的var关键字。

possibleGuess = inputField.text.toInt()

也不需要显式类型注释,因为类型已经定义。

关于ios - Xcode 中的流控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885023/

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