I found an interesting code in my project and I'm wondering how it even works. If I simplify it, in a playground it looks like this:
var b: Bool = truevar n: NSNumber = b as NSNumber
I don't understand why as
operator casts Bool
to NSNumber
. Documentation for as
gives the only example for using it, namely for checking a type of an element in the array of [Any]
. That's an example from Docs and that's how I expected as
to be used:
var things = [Any]()for thing in things { switch thing { case 0 as Int: case 0 as Double:
I didn't expect as
to do a real casting. Where can I read more about it?When I try similar code with Int
instead of NSNumber
, it doesn't compile:
var b: Bool = truevar n: Int = b as Int --> doesn't compile
So NSNumber
seems to be a special case? I'm confused. Can anyone shed light on this?