Which is the Swift equivalent of isnan()?

Alberto Bellini picture Alberto Bellini · Jun 22, 2014 · Viewed 23.5k times · Source

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

Answer

Mick MacCallum picture Mick MacCallum · Jun 22, 2014

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

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.

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


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)
}

Its values are declared in the FloatingPointClassification enum.