What is the Swift equivalent of isnan ()?

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

+53
cocoa swift nan
Jun 22 '14 at 12:48
source share
2 answers

It is defined in the protocol FloatingPointNumber , which both Float and Double match. The following is used:

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

If you are looking for a way to do this check yourself, you can. IEEE determines that NaN! = NaN, that is, you cannot directly compare NaN with a number to determine its value-number. However, you can verify that maybeNaN != maybeNaN . If this condition evaluates to true, you are dealing with NaN.

Although you need to use aVariable.isNaN to determine if the value is NaN.




As a quick note, if you are less sure about the classification of the value you are working with, you can switch the value of your FloatingPointNumber corresponding floatingPointClass type.

 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 listing.

+108
Jun 22 '14 at 12:51 on
source share

The accepted answer works, but when I first saw it, I did not quite understand because of the example.

Here is an example from Apple for those who are not clear:

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") } 
0
May 20 '19 at 19:16
source share



All Articles