Forced Casting with as! and Its Risks
Use as! only when a cast is guaranteed to succeed.
Forced Casting
The forced cast operator as! downcasts and unwraps in one step. It gives you the non-optional type directly, but crashes if the cast fails.
class Animal {
let name: String
init(name: String) { self.name = name }
}
class Dog: Animal {
func bark() -> String { return name + " says Woof" }
}
class Cat: Animal {
func meow() -> String { return name + " says Meow" }
}
let a: Animal = Dog(name: "Rex")
let dog = a as! Dog
print(dog.bark())No Optional Wrapping
Unlike as?, the result of as! is the plain type, not an optional. There is nothing to unwrap.
class Animal {
let name: String
init(name: String) { self.name = name }
}
class Dog: Animal {
func bark() -> String { return name + " says Woof" }
}
class Cat: Animal {
func meow() -> String { return name + " says Meow" }
}
let a: Animal = Dog(name: "Rex")
let dog: Dog = a as! Dog
print(type(of: dog))All lessons in this course
- Upcasting and Downcasting Basics
- Conditional Casting with as?
- Forced Casting with as! and Its Risks
- Checking Types with is