Swift等同于isnan()?

时间:2014-06-22 12:48:01

标签: cocoa swift nan

这相当于Swift中的isnan()? 我需要检查一些操作结果是否有效并删除那些无效的x / 0 感谢

2 个答案:

答案 0 :(得分:109)

FloatingPointNumber协议中定义了FloatDouble类型符合的协议。用法如下:

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。

虽然您应更喜欢使用aVariable.isNaN 来确定某个值是否为NaN。


作为一个侧面说明,如果您对您正在使用的值的分类不太确定,则可以切换FloatingPointNumber符合类型'的值。 s floatingPointClass财产。

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枚号中声明。

答案 1 :(得分:0)

可接受的答案有效,但是当我第一次看到它时,由于示例的原因,我并不十分清楚,我也不知道NaN是"not a number"的缩写。

以下是苹果公司为不清楚的人提供的示例:

enter image description here

let x = 0.0
let y = x * .infinity // y is a NaN

if y.isNan {

    print("this is NaN") // this will print
} else {

    print("this isn't Nan")
}