ios - Xcode 中的流控制

标签 ios xcode

出于某种原因,即使输入了一个有效输入,即一个整数,它似乎确实进入了函数中的 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/

相关文章:

swift - 无法在强制转换中将类型 'String?' 的值转换为类型 'NSString'

iOS 使用来自应用程序的给定关键字打开 iTunes 音乐搜索

ios - 初学者核心数据和关系

iphone - 清晰的上下文图形

ios - 如何在 AR 套件中旋转或缩放 3D 模型 scn 文件

ios - 在 Xcode 中使用预处理器处理命令行选项

iphone - 如何检查 iPhone 上使用的缓存磁盘空间量

ios - iOS/Mac 的地址字段验证

ios - 防止 Xcode 在为 iOS 运行时准备 Apple Watch

iphone - 如何将 -mthumb 添加到 Xcode