0Pricing
Swift Academy · Lesson

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

  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