Which is the Swift equivalent of isnan()?

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.


The accepted answer works but when I first saw it I wasn't exactly clear because of the example and i didn't know that NaN is an acronym for "not a number".

Here's an example from Apple for anyone who isn't clear:

enter image description here

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

if y.isNan {

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

    print("this isn't Nan")
}

Tags:

Cocoa

Swift

Nan