Swift Academy · Lesson

Forced Casting with as! and Its Risks

Use as! only when a cast is guaranteed to succeed.

Lesson 3 of 413 steps

Forced Casting with as! and Its Risks is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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))

The Risk of as!

If the instance is not actually the target type, as! triggers a runtime trap and stops the program. There is no recovery.

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 cat = a as! Cat  // would crash at runtime
print("Only force-cast when certain")

When Forced Casting Is Safe

Use as! only when you are absolutely certain of the type, for example right after checking with is.

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")
if a is Dog {
    let dog = a as! Dog
    print(dog.bark())
}

Forced Cast After a Guarantee

If your code logic guarantees the type, a forced cast documents that certainty. Still, prefer as? when unsure.

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" }
}
func barkIfDog(_ a: Animal) {
    guard a is Dog else { return }
    let dog = a as! Dog
    print(dog.bark())
}
barkIfDog(Dog(name: "Rex"))

Comparing as? and as!

as? is safe and returns an optional; as! is forceful and crashes on failure. Choose based on how certain you are.

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 safe = a as? Dog
let forced = a as! Dog
print(safe?.bark() ?? "nil")
print(forced.bark())

Force Casting Collections

Forced casts also work on whole collections, like array as! [Dog], but the same crash risk applies to every element.

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 animals: [Animal] = [Dog(name: "Rex"), Dog(name: "Buddy")]
let dogs = animals as! [Dog]
for d in dogs { print(d.bark()) }

A Dangerous Pattern

Force casting an array that contains a wrong element crashes. This is why mixed collections should use as? per element.

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 animals: [Animal] = [Dog(name: "Rex"), Cat(name: "Mia")]
// let dogs = animals as! [Dog] // would crash on the Cat
for a in animals {
    if let d = a as? Dog { print(d.bark()) }
}

Force Unwrap vs Force Cast

The ! in as! is conceptually like force-unwrapping an optional: convenient but dangerous if the assumption is wrong.

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 viaOptional = (a as? Dog)!
let viaForce = a as! Dog
print(viaOptional.name, viaForce.name)

Best Practice

Default to as?. Reserve as! for cases where a failure would indicate a programmer error you want to surface immediately during development.

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" }
}
func process(_ a: Animal) -> String {
    if let d = a as? Dog { return d.bark() }
    return "not a dog"
}
print(process(Dog(name: "Rex")))
print(process(Cat(name: "Mia")))

Forced Cast Summary Example

When the type is verified, as! reads cleanly. When in doubt, the safe conditional cast is the right tool.

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 known: Animal = Dog(name: "Rex")
if known is Dog {
    print((known as! Dog).bark())
}

Quick Check

Reason about the danger of forced casting.

Recap: Forced Casting and Its Risks

You learned that as! downcasts and unwraps to a non-optional type but crashes on failure, that it should only be used when the type is certain (often after an is check), and that as? remains the safer default.

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")
if a is Dog { print((a as! Dog).bark()) } else { print("safe skip") }
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Forced Casting with as! and Its Risks” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Forced Casting with as! and Its Risks”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Forced Casting with as! and Its Risks”?

Use as! only when a cast is guaranteed to succeed. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Forced Casting with as! and Its Risks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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