Swift2 如何在Swift 2中检查非数字(NaN)
以下方法使用两个变量计算百分比Swift2 如何在Swift 2中检查非数字(NaN),swift2,Swift2,以下方法使用两个变量计算百分比 func casePercentage() { let percentage = Int(Double(cases) / Double(calls) * 100) percentageLabel.stringValue = String(percentage) + "%" } 除cases=1和calls=0外,上述方法运行良好。 这会产生一个致命错误:浮点值无法转换为Int,因为它是无穷大或NaN 因此,我创建了这个变通方法:
func casePercentage() {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
}
除cases=1和calls=0外,上述方法运行良好。
这会产生一个致命错误:浮点值无法转换为Int,因为它是无穷大或NaN
因此,我创建了这个变通方法:
func casePercentage() {
if calls != 0 {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
} else {
percentageLabel.stringValue = "0%"
}
}
这不会给出错误,但在其他语言中,可以使用.isNaN()方法检查变量。这在Swift2中是如何工作的 您可以使用命令“强制展开”可选类型代码>操作员:
calls! //asserts that calls is NOT nil and gives a non-optional type
但是,如果它是nil
,则会导致运行时错误
防止使用nil
或0的一个选项是执行您所做的操作并检查它是否为0
第二个选项是nil
-检查
if calls != nil
第三个(也是最快捷的)选项是使用if let
结构:
if let nonNilCalls = calls {
//...
}
如果调用为nil
,则if
块的内部不会运行
请注意,nil
-检查和if let
不会保护您不被0除。你必须单独检查
结合第二种方法和您的方法:
//calls can neither be nil nor <= 0
if calls != nil && calls > 0
//调用既不能为nil也不能为0
您可以使用命令“强制展开”可选类型代码>操作员:
calls! //asserts that calls is NOT nil and gives a non-optional type
但是,如果它是nil
,则会导致运行时错误
防止使用nil
或0的一个选项是执行您所做的操作并检查它是否为0
第二个选项是nil
-检查
if calls != nil
第三个(也是最快捷的)选项是使用if let
结构:
if let nonNilCalls = calls {
//...
}
如果调用为nil
,则if
块的内部不会运行
请注意,nil
-检查和if let
不会保护您不被0除。你必须单独检查
结合第二种方法和您的方法:
//calls can neither be nil nor <= 0
if calls != nil && calls > 0
//调用既不能为nil也不能为0
@Cosyn我读了那个链接,但作为一个n00b,它对我来说没有任何意义。@Cosyn我读了那个链接,但作为一个n00b,它对我来说没有任何意义。