0Pricing
Swift Academy · Lesson

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

  1. Upcasting and Downcasting Basics
  2. Conditional Casting with as?
  3. Forced Casting with as! and Its Risks
  4. Checking Types with is
← Back to Swift Academy