March 2017
Intermediate to advanced
226 pages
5h 13m
English
Type casting enables you to reinterpret an instance’s type at runtime. Swift offers three such operators: as, as?, and as!. These operators cast instances to other types by downcasting (converting to a more specialized type) or upcasting (converting to a less-specialized, typically type-erased, type). Casting is most commonly encountered when working with type-erased collections, such as web-sourced JSON data. Any erased type (Any, AnyHashable, AnyObject), protocol, or root class (NSObject) offers a likely opportunity to work with Swift type casting.
The type-checking is operator tests whether an instance can be resolved to another type:
| | // If you try this code in a playground, ignore |
| | // the warnings, as these values ... |
Read now
Unlock full access