Type casting in Swift enables you to check and interpret the type of a class instance at runtime. This is particularly useful when working with hierarchies of classes or protocols, allowing you to treat objects as instances of their superclass or a specific subclass. There are two types of type casting in Swift: ‘as?’ for optional type casting and as! for forced type casting.
class Animal {
func makeSound() {
print("Animal makes a sound")
}
}
class Dog: Animal {
func bark() {
print("Dog barks")
}
}
let animal = Animal()
let dog = Dog()
let animals: [Any] = [animal, dog]
for animal in animals {
if let dog = animal as? Dog {
dog.bark()
} else if let animal = animal as? Animal {
animal.makeSound()
}
}