本文介绍了哪个是 isnan() 的 Swift 等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个是 Swift 中 isnan() 的等价物?我需要检查一些操作结果是否有效并删除那些无效的,例如 x/0谢谢

Which is the equivalent of isnan() in Swift ?I need to check if some operation results are valid and delete those invalid like x/0Thanks

推荐答案

它是在 FloatingPointNumber 协议中定义的,它既FloatDouble 类型符合.用法如下:

It's defined in the FloatingPointNumber protocol, which both the Float and Double types conform to. Usage is as follows:

let d = 3.0
let isNan = d.isNaN // False

let d = Double.NaN
let isNan = d.isNaN // True

如果您正在寻找自己进行此检查的方法,则可以.IEEE 定义 NaN != NaN,这意味着您不能直接将 NaN 与数字进行比较以确定其是否为数字.但是,您可以检查 maybeNaN !=maybeNaN.如果此条件评估为真,则您正在处理 NaN.

If you're looking for a way to make this check yourself, you can. IEEE defines that NaN != NaN, meaning you can't directly compare NaN to a number to determine its is-a-number-ness. However, you can check that maybeNaN != maybeNaN. If this condition evaluates as true, you're dealing with NaN.

尽管您应该更喜欢使用 aVariable.isNaN 来确定值是否为 NaN.

Although you should prefer using aVariable.isNaN to determine if a value is NaN.

顺便提一下,如果您对正在使用的值的分类不太确定,您可以切换 FloatingPointNumber 符合类型的 floatingPointClass 的值 属性.

As a bit of a side note, if you're less sure about the classification of the value you're working with, you can switch over value of your FloatingPointNumber conforming type's floatingPointClass property.

let noClueWhatThisIs: Double = // ...

switch noClueWhatThisIs.floatingPointClass {
case .SignalingNaN:
    print(FloatingPointClassification.SignalingNaN)
case .QuietNaN:
    print(FloatingPointClassification.QuietNaN)
case .NegativeInfinity:
    print(FloatingPointClassification.NegativeInfinity)
case .NegativeNormal:
    print(FloatingPointClassification.NegativeNormal)
case .NegativeSubnormal:
    print(FloatingPointClassification.NegativeSubnormal)
case .NegativeZero:
    print(FloatingPointClassification.NegativeZero)
case .PositiveZero:
    print(FloatingPointClassification.PositiveZero)
case .PositiveSubnormal:
    print(FloatingPointClassification.PositiveSubnormal)
case .PositiveNormal:
    print(FloatingPointClassification.PositiveNormal)
case .PositiveInfinity:
    print(FloatingPointClassification.PositiveInfinity)
}

它的值在 FloatingPointClassification 枚举中声明.

Its values are declared in the FloatingPointClassification enum.

这篇关于哪个是 isnan() 的 Swift 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 00:14
查看更多