In Swift, what do the is, as?, as! and as operators each do, and which one fits a downcast that might fail?
answer
- four operators, one compile-time
- Bool, Optional, value-or-crash
- upcast and bridging need no check
- downcast of unknown outcome: optional binding
basics
~20 sis returns a Bool; as? returns an optional, nil on failure; as! returns the value or traps; plain as only does conversions the compiler proves, such as upcasts and bridging. A downcast that might fail takes as?.
solid answer
~50 s`is`, `as?` and `as!` check the **run-time type** of a value whose static type is more general, such as a superclass, `Any` or a protocol; plain `as` is settled at compile time. `x is T` returns a `Bool` and changes nothing: inside `if event is PurchaseEvent` the compiler still sees an `AnalyticsEvent`. `x as? T` returns `T?`, nil when the cast fails, so it pairs with `if let` or `guard let`. `x as! T` returns a plain `T` and traps when the cast fails; the reference defines it as `(x as? T)!`. Plain `as` performs only conversions the compiler can prove at compile time: an **upcast** to a superclass or protocol, a **bridging** conversion such as `String` to `NSString`, or a type coercion like `x as Any`. A downcast whose outcome you cannot guarantee, an event from a queue or a value from a `[String: Any]` payload, takes `as?`.
code
swift · 25 linesclass AnalyticsEvent {
let name: String
init(name: String) { self.name = name }
}
class PurchaseEvent: AnalyticsEvent {
let amountInCents: Int
init(amountInCents: Int) {
self.amountInCents = amountInCents
super.init(name: "purchase")
}
}
let queue: [AnalyticsEvent] = [AnalyticsEvent(name: "launch"), PurchaseEvent(amountInCents: 499)]
for event in queue {
print(event.name, event is PurchaseEvent) // is: a Bool, no conversion
if let purchase = event as? PurchaseEvent { // as?: PurchaseEvent?
print("revenue:", purchase.amountInCents)
}
}
let purchase = queue[1] as! PurchaseEvent // as!: traps if queue[1] is not a PurchaseEvent
let general = purchase as AnalyticsEvent // as: upcast the compiler proves
print(general.name)go deeper
Recall the four forms and their result types: Bool, optional, plain value with a trap, and the compile-time as. Show if let with as? on a class hierarchy.
Explain that as? and as! check the dynamic type at run time and return the same instance, and that as! is defined as the force-unwrapped as?.
Read the compiler's cast warnings as review signals, and explain why accepting the as! fix-it on a downcast error is usually the wrong repair.
Treat a growing number of downcasts as a design smell and ask whether a protocol requirement or generic parameter would keep the type known statically.
## The four operators at a glance Swift checks and converts types with two keywords, `is` and `as`, and `as` comes in three forms; three of the four spellings act at run time. They matter whenever the **static type** the compiler knows (a superclass such as `AnalyticsEvent`, the type `Any`, a protocol) is more general than the **dynamic type** the value really has (a `PurchaseEvent`, an `Int`, a concrete conformer). | Operator | Result type | On failure | Checked when | |---|---|---|---| | `x is T` | `Bool` | `false` | run time | | `x as? T` | `T?` | `nil` | run time | | `x as! T` | `T` | the process traps | run time | | `x as T` | `T` | does not compile | compile time | - **`is`** answers a yes-or-no question and converts nothing. Swift does not narrow the variable afterwards: after `if event is PurchaseEvent`, reading `event.amountInCents` is still a compile error, because `event` is still typed `AnalyticsEvent`. - **`as?`** is the conditional downcast. It returns an optional, which you unwrap with `if let` or `guard let`. - **`as!`** is the forced downcast. The language reference defines `x as! T` as behaving like `(x as? T)!`, so it traps on a wrong type and also on a nil input. - **`as`** without punctuation is for conversions that always succeed: an upcast, a bridging conversion such as `title as NSString`, or a coercion that picks an overload or silences a warning, such as `optionalValue as Any`. ## Downcasting through a class hierarchy Take an analytics queue typed `[AnalyticsEvent]` that holds base events and `PurchaseEvent` subclass instances. Iterating gives you values typed `AnalyticsEvent`; to read `amountInCents` you must downcast: 1. Write `if let purchase = event as? PurchaseEvent { … }`. 2. At run time Swift checks whether the instance is a `PurchaseEvent` or a subclass of it. 3. On success, `purchase` refers to **the same instance**, now typed `PurchaseEvent`. Nothing is copied or converted; the book is explicit that casting does not modify the instance. 4. On failure, the expression is `nil` and the `else` branch runs. The same operators check protocol conformance: `value as? CustomStringConvertible` succeeds when the dynamic type conforms. They also pull concrete values back out of `Any`: `payload["screen"] as? String` from a legacy SDK's `[String: Any]`. ## What the compiler tells you Swift 6.4 diagnoses casts whose outcome it already knows. These are **warnings**, even though the reference manual's prose says a guaranteed `as?` raises an error: - `'is' test is always true`, for `purchase is AnalyticsEvent`. - `conditional cast from 'PurchaseEvent' to 'AnalyticsEvent' always succeeds`, for an `as?` that could be a plain `as`. - `forced cast of 'PurchaseEvent' to same type has no effect`. - `cast from 'String' to unrelated type 'Int' always fails`. A plain `as` used for a downcast is an **error**: `'AnalyticsEvent' is not convertible to 'PurchaseEvent'`, with the note `did you mean to use 'as!' to force downcast?`. Accepting that fix-it without thinking is how many forced casts enter a codebase; `as?` is usually the better repair. ## Choosing the operator - Use **`is`** when you only need a count or a branch and never the converted value. - Use **`as?`** whenever the cast can fail for reasons outside the current function: data from a queue, a payload, a plug-in or another module. - Use **`as!`** only where a failure would be a programmer error that the surrounding code itself rules out. - Use **`as`** for upcasts and bridging, and to make a conversion explicit where an implicit one would warn. ## Common mistakes - Expecting `is` to narrow the variable's type, as some languages do. - Believing `as?` builds a new object of the target class; it hands back the same instance. - Treating `as!` as a faster `as?`; it performs the same run-time check and then traps. - Wrapping `as!` in `do`-`catch`; a failed cast is not a thrown error, so nothing can catch it. - Reaching for casts where a generic parameter or a protocol requirement would keep the type static; the Swift material on generic constraints covers that route.
- What does x as! T do when x is nil, for example a missing key in a [String: Any] dictionary?It traps. The reference defines `x as! T` as `(x as? T)!`, so a nil input makes `as?` return nil and the force unwrap fails with `Unexpectedly found nil while unwrapping an Optional value`. A forced cast on a dictionary lookup therefore crashes on a missing key as well as on a wrong type.
- Why does event as PurchaseEvent fail to compile when event is typed AnalyticsEvent?Plain `as` only performs conversions the compiler can prove, and a superclass reference might hold any subclass. Swift 6.4 reports `'AnalyticsEvent' is not convertible to 'PurchaseEvent'` and suggests `as!`. The safer repair is usually `as?` with optional binding, keeping the failure path visible.
- After if let purchase = event as? PurchaseEvent, is purchase a copy of event?No. For a class instance the cast returns the same reference with a more specific static type, so `purchase === event` is true and a change through one is visible through the other. Casting changes how the compiler lets you use the instance, not the instance.
- as? turns the object into a new instance of the subclass.
- as! is a faster as? because it skips the run-time check.
- After if event is PurchaseEvent, the subclass properties are available on event.
- Plain as can downcast when you are sure of the subclass.
- A failed as! throws an error that do-catch can handle.