Forced Casting with as! and Its Risks
Use as! only when a cast is guaranteed to succeed.
Forced Casting with as! and Its Risks is a free Swift Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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") }Frequently asked questions
Is the “Forced Casting with as! and Its Risks” lesson free?
Yes — the full text of “Forced Casting with as! and Its Risks” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
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; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
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
- Upcasting and Downcasting Basics
- Conditional Casting with as?
- Forced Casting with as! and Its Risks
- Checking Types with is