对错误消息感到困惑(lldb)

时间:2015-01-27 09:40:53

标签: swift null

假设示例13已输入文本字段,该字段由以下引用:numberField

@IBAction func calculateButton(sender: AnyObject) {

            var numInt = numberField.text.toInt()

            println(numInt) //outputs Optional(13)
            println(numInt!) //outputs 13

            if numInt != nil {

                var unwrappedNum = numInt!
                var isPrime = true
                println(unwrappedNum) //Crashes here and outputs (lldb)

                for var i = 1; i<unwrappedNum; i++ {
                    if unwrappedNum % i == 0 {
                        isPrime = false

                    }
                }
            }
}

我已经在网上查了一下,我认为问题在于它正在评估为零,但是我不明白在if语句之外它是如何评价nil的。它不是nil。

2 个答案:

答案 0 :(得分:1)

而不是nil检查,快速执行此操作是使用可选绑定

if let unwrappedNum = numInt
{
    println(unwrappedNum)
}

或者只是你可以做

if let numInt = numberField.text.toInt()
{
    println(numInt)
}

numInt将被解开。

欲了解更多信息,请阅读:http://www.appcoda.com/beginners-guide-optionals-swift/

答案 1 :(得分:0)

哦,我看到你的问题是:

var numInt = numberField.text.toInt()

当“numberField.Text”为空字符串时,它会崩溃。

相关问题