Quantcast
Channel: Swift casts Bool to NSNumber using 'as' operator - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Dávid Pásztor for Swift casts Bool to NSNumber using 'as' operator

$
0
0

The as operator can be used for two types of casting. Type casting and bridge casting. Type casting can be used to convert subclasses to superclasses (called upcasting) or to downcast superclasses to subclasses (only works if first the subclass instance was upcasted). This is what you see in your example with the Any array.

Bridge casting is however a mechanisms provided for easier interoperability between Foundation and Swift classes. NSNumber has an init method that takes a Bool as its input argument. The as operator in your example calls this initializer, so

var b: Bool = truevar n: NSNumber = b as NSNumber

is just a shorthand notation for

var b:Bool = truevar n = NSNumber(value: b)

Int and Bool are both Swift types, so bridge casting doesn't work on them.

For more information, check the documentation of NSNumber.


Viewing all articles
Browse latest Browse all 4

Trending Articles