的toInt()
方法返回一个可选价值,因为该字符串它正试图转换可能不包含一个适当的值。例如,这些字符串将被转换为nil
:"house"
,"3.7"
,""
(空字符串)。
由于值可以是nil
,toInt()
返回一个可选Int
这是类型Int?
。如果不先解开它,则无法使用该值。这就是你收到错误信息的原因。以下是处理此问题的两种安全方法:
您需要决定在值无法转换时要执行的操作。如果你只是想在这种情况下使用0
,然后用零合并运算(??
)像这样:
let number1 = field1.text.toInt() ?? 0
// number1 now has the unwrapped Int from field1 or 0 if it couldn't be converted
let number2 = field2.text.toInt() ?? 0
// number2 now has the unwrapped Int from field2 or 0 if it couldn't be converted
let duration = number1 * number2
mylabel.text = "\(duration)"
如果你希望你的程序做什么,除非这两个领域都有效值:
if let number1 = field1.text.toInt() {
// if we get here, number1 contains the valid unwrapped Int from field1
if let number2 = field2.text.toInt() {
// if we get here, number2 contains the valid unwrapped Int from field2
let duration = number1 * number2
mylabel.text = "\(duration)"
}
}
那么,当你说你的意思是使用!
时,错误信息是什么意思。您可以通过在最后添加!
来打开可选值,但是您必须确保该值不是第一个,否则您的应用将崩溃。所以你也可以这样做:
if number1 != nil && number2 != nil {
let duration = number1! * number2!
mylabel.text = "\(duration)"
}
你的问题是什么? – 2014-08-31 04:55:37
变量不能有空格。这:'Number1','Number2'。 **不是这个**:'Number 1','Number 2'。 – 2014-08-31 05:33:14
你遇到什么问题?从我们可以看到的代码中,它应该正常工作(除了变量名称中的空格)。 – drewag 2014-08-31 06:20:15