Type Casting: is, as?, as! and as
Checking and converting types safely with Swift's casting operators.
What is Type Casting?
Type casting lets you check or convert an instance to a different class in its hierarchy.
class Animal { var name: String = "Animal" }
class Dog: Animal { func bark() { print("Woof") } }
let a: Animal = Dog()
print(a.name)The is Operator
Use is to check whether an instance is of a certain subclass.
let a: Animal = Dog()
if a is Dog {
print("It's a dog")
}All lessons in this course
- Class Inheritance and the super Keyword
- override, final and Preventing Subclassing
- Type Casting: is, as?, as! and as
- Deinitializers and Memory Lifecycle