'Int'类型的值永远不能为零,swift 2.2中不允许比较

时间:2016-03-23 05:38:11

标签: ios swift

if(Int(textfield.text!)! != nil) { //value of type 'Int' can never be nil, comparison isn't allowed.

  //Rest of the code
 }

一切都运行正常,但昨天我更新了我的Xcode,因为我收到了这个错误。请帮忙。

2 个答案:

答案 0 :(得分:3)

要检查nil,只需删除尾随的感叹号,以便将Int初始化程序的结果保留为可选。

if Int(textfield.text!) != nil {

  //Rest of the code
}

答案 1 :(得分:0)

你强行打开Int:

Int(textField.text!)! //这句凄惨的感叹(砰)说,相信我,这不是一个零

然后你试图通过!= nil

查看它是否为零

我建议您对选项进行适当的解包,如下:

if let textInt = textField.text, integerUnwrapped = Int(textInt) {
  // Rest of the code
} else {
  // Handle if either the text or integer is actually nil
}

如果由于某种原因textField.text获取了一个字符串,则此代码将在else语句中失败。

您处理强制可选解包的方式会导致崩溃。