以下方法使用两个变量计算百分比。
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中如何工作?
The following method calculates the percentage using two variables.
func casePercentage() { let percentage = Int(Double(cases) / Double(calls) * 100) percentageLabel.stringValue = String(percentage) + "%" }The above method is functioning well except when cases = 1 and calls = 0. This gives a fatal error: floating point value can not be converted to Int because it is either infinite or NaN
So I created this workaround:
func casePercentage() { if calls != 0 { let percentage = Int(Double(cases) / Double(calls) * 100) percentageLabel.stringValue = String(percentage) + "%" } else { percentageLabel.stringValue = "0%" } }This will give no errors but in other languages you can check a variable with an .isNaN() method. How does this work within Swift2?
最满意答案
您可以使用! “强制拆包”可选类型! 运营商:
calls! //asserts that calls is NOT nil and gives a non-optional type但是,如果它nil ,则会导致运行时错误。
防止使用nil或0的一种选择是做你所做的事情,并检查它是否为0。
其次是选项是nil
if calls != nil第三个(也是最Swift-y)选项是使用if let结构:
if let nonNilCalls = calls { //... }如果calls nil , if块的内部将不会运行。
请注意, nil检查, if let 不会保护你不被0除。你将不得不单独检查。
结合第二和你的方法:
//calls can neither be nil nor <= 0 if calls != nil && calls > 0You can "force unwrap" the optional type using the ! operator:
calls! //asserts that calls is NOT nil and gives a non-optional typeHowever, this will result in a runtime error if it is nil.
One option to prevent using nil or 0 is to do what you have done and check if it's 0.
The second is option is to nil-check
if calls != nilThe third (and most Swift-y) option is to use the if let structure:
if let nonNilCalls = calls { //... }The inside of the if block won't run if calls is nil.
Note that nil-checking and if let will NOT protect you from dividing by 0. You will have to check for that separately.
Combining second and your method:
//calls can neither be nil nor <= 0 if calls != nil && calls > 0更多推荐
发布评论