Swift Type Casting
Type casting is the process of checking the type of an instance, and/or treating that instance as if it is a different superclass or subclass from its actual type. Swift provides two types of type casting: Upcasting and Downcasting.
Swift Upcasting
Upcasting is the process of casting a subclass instance to a superclass instance. It is always safe and does not require the use of the as
keyword. Once the instance is upcasted, only the members of the superclass are accessible.
1class Animal { 2 func makeSound() { 3 print("...") 4 } 5} 6 7class Dog: Animal { 8 override func makeSound() { 9 print("Bark") 10 } 11} 12 13let dog: Dog = Dog() 14let animal: Animal = dog 15 16dog.makeSound() // Output: Bark 17animal.makeSound() // Output: Bark
In the example above, the Dog
instance is upcasted to an Animal
instance, and the makeSound()
method is called on both instances.
Swift Downcasting
Downcasting is the process of casting a superclass instance to a subclass instance. It is not always safe and requires the use of the as?
or as!
keyword. The as?
keyword returns an optional value, which is nil
if the downcasting fails. The as!
keyword force unwraps the optional, and will cause a runtime error if the downcasting fails.
1class Animal { 2 func makeSound() { 3 print("...") 4 } 5} 6 7class Dog: Animal { 8 override func makeSound() { 9 print("Bark") 10 } 11} 12 13let animal: Animal = Animal() 14let dog1: Dog? = animal as? Dog 15let dog2: Dog! = animal as! Dog // Error: Fatal error: Unexpectedly found nil while unwrapping an Optional value 16 17if let dog = animal as? Dog { 18 dog.makeSound() 19} else { 20 print("animal is not a dog") 21}
In the example above, the Animal
instance is downcasted to a Dog
instance using both as?
and as!
. Since the Animal
instance is not a Dog
instance, the as!
keyword causes a runtime error. The as?
keyword returns nil
, so the code inside the if let
statement is not executed.
Swift Type Checking
Type checking is the process of checking the type of an instance using the is
keyword. It returns a boolean value indicating whether the instance is of a certain type.
1class Animal { 2 func makeSound() { 3 print("...") 4 } 5} 6 7class Dog: Animal { 8 override func makeSound() { 9 print("Bark") 10 } 11} 12 13let animal: Animal = Animal() 14let dog: Dog = Dog() 15 16print(animal is Dog) // Output: false 17print(dog is Animal) // Output: true
In the example above, the type of the animal
instance is checked to see if it is a Dog
instance, which returns false
. The type of the dog
instance is checked to see if it is an Animal
instance, which returns true
.
Type casting is an important feature of Swift, allowing us to treat an instance as if it is a different superclass or subclass. Upcasting is always safe, while downcasting requires the use of the as?
or as!
keyword. Type checking allows us to check the type of an instance using the is
keyword.