skip to content

Casting and Metatypes

Casting checks or converts types at run time with is, as? and as!, and metatypes treat types as values. Interviewers ask when as! is acceptable and what Any and AnyObject accept.

on this pageshow

explore

questions

6

In Swift, what do the is, as?, as! and as operators each do, and which one fits a downcast that might fail?

level: juniorimportance: must knowfreq 75%

answer

  1. four operators, one compile-time
  2. Bool, Optional, value-or-crash
  3. upcast and bridging need no check
  4. downcast of unknown outcome: optional binding

basics

~20 s

is 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 lines
swift
class 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

for a junior

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.

for a middle

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?.

for a senior

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.

for a principal

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.
open as a page

In Swift, when does an as! forced cast trap at run time, and when is it acceptable instead of as? in production code?

level: middleimportance: must knowfreq 62%

basics

~20 s

as! traps whenever the cast fails, including when the input is nil. It is acceptable only where failure would be a programmer error the same code rules out, such as a type it registered itself; data from outside takes as?.

open as a page

In Swift, what values can Any and AnyObject each hold, and what happens when a struct is stored as AnyObject?

level: middleimportance: should knowfreq 50%

basics

~20 s

Any holds a value of any type, including structs, closures, metatypes and optionals. AnyObject holds class instances, so a struct needs an explicit as AnyObject, which bridges it or wraps it in a new box object.

open as a page

In Swift, what are .Type, .self and type(of:), and how does a plug-in registry store types and create instances from them?

level: middleimportance: should knowfreq 40%

basics

~20 s

T.Type is the type of the type T, T.self is that type as a value, and type(of:) returns a value's dynamic type. A registry stores metatypes such as any Plugin.Type and creates instances with .init().

open as a page

In Swift, why does a JSONSerialization payload's 2.5 fail as? Int while 3.0 succeeds, and what does as? [Int] check?

level: seniorimportance: should knowfreq 35%

basics

~20 s

JSONSerialization stores numbers as NSNumber, and a cast to a Swift numeric type succeeds only when the value fits that type exactly: 3.0 becomes 3, 2.5 gives nil. as? [Int] checks every element and returns nil if any one fails.

open as a page

A Swift analytics payload typed [String: Any] stores an Optional that is nil: why does comparing it to nil return false, and what do as? casts do with it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

An Any can hold an Optional as its value, so an Any containing Optional.none is not nil and == nil is always false. A cast such as as? Int looks inside: a stored nil gives nil, a stored 5 gives 5.

open as a page