After upgrading to Xcode 9.3 (9E145) my App showed some unexpected behavior. It seems that the issue is with a cast of an NSNumber to a Float. I use the as
type cast operator for this. See the following example.
let n = NSNumber.init(value: 1.12)
let m = NSNumber.init(value: 1.00)
let x = n as? Float
let y = m as? Float
let xd = n as? Double
let z = Float(truncating: n)
Here, the first cast fails, i.e. x == nil
. The second cast succeeds and the instantiation of a Float with the init:truncating
constructor also succeeds, i.e. z == 1.12
. The cast of n to a Double succeeds, which, to me, makes no sense at all.
Can anyone explain this behavior to me? I.e. can anyone give me a good reason why the cast of n to a Float fails? Is this a bug? If this is intended behavior, can you please reference the location in the Swift documentation that describes this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…