Swift BasicsLesson 10Free preview
Swift Type Casting
This lesson is part of Swift · All levels
Summary
This lesson reviews Type Casting in Swift to check the object type or treat the object as another subtype. Swift provides an 'ice' operator for type checking as well as an 'as?' operator (safe downcasting) and an 'as!' operator (forced downcasting). Understanding casting is crucial in the hierarchy of inheritance and protocol.
Key points
- The 'is' operator returns the boolean value to check whether the object is a particular type of instance
- Operator 'as?' tries to do the downcast and return Optional (zero value if failed)
- The 'ass!' operator forces downcast and will trigger a crash if the type does not fit
- Any can represent any instance type, and AnyObject represents any instance class.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.