Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the Swift equivalent of isnan()?

Tags:

swift

cocoa

nan

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

like image 308
Alberto Bellini Avatar asked Jun 22 '14 12:06

Alberto Bellini


1 Answers

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.

like image 144
Mick MacCallum Avatar answered Oct 11 '22 13:10

Mick MacCallum