Conditional Casting with as?
Attempt a cast that returns an optional on failure.
Conditional Casting
The conditional cast operator as? attempts a downcast and returns an optional: the value wrapped if it succeeds, or nil if it 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 maybe = a as? Dog
print(maybe != nil)Result Is Optional
Because the cast might fail, the result type is Dog?, not Dog. You must unwrap it before use.
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 maybe: Dog? = a as? Dog
print(type(of: maybe))All lessons in this course
- Upcasting and Downcasting Basics
- Conditional Casting with as?
- Forced Casting with as! and Its Risks
- Checking Types with is