如何检查Swift 2中的非数字(NaN)(How to check for a Not a Number (NaN) in Swift 2)

编程入门 行业动态 更新时间:2024-10-26 20:24:40
如何检查Swift 2中的非数字(NaN)(How to check for a Not a Number (NaN) in Swift 2)

以下方法使用两个变量计算百分比。

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 > 0

You can "force unwrap" the optional type using the ! operator:

calls! //asserts that calls is NOT nil and gives a non-optional type

However, 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 != nil

The 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

更多推荐

本文发布于:2023-07-31 06:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Swift   NaN   Number   check

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!