Tutorial by Examples

A variable can be downcasted to a subtype using the type cast operators as?, and as!. The as? operator attempts to cast to a subtype. It can fail, therefore it returns an optional. let value: Any = "John" let name = value as? String print(name) // prints Optional("John") ...
The switch statement can also be used to attempt casting into different types: func checkType(_ value: Any) -> String { switch value { // The `is` operator can be used to check a type case is Double: return "value is a Double" // The `as` operator will ...
The as operator will cast to a supertype. As it cannot fail, it does not return an optional. let name = "Ringo" let value = string as Any // `value` is of type `Any` now
A downcast can be used to make use of a subclass's code and data inside of a function taking a parameter of its superclass. class Rat { var color = "white" } class PetRat: Rat { var name = "Spot" } func nameOfRat(🐭: Rat) -> String { guard let petRat = ...
Type Casting Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and express...

Page 1 of 1