skip to content

Generics and Abstraction

Generic code, opaque and existential types, and runtime casting: how Swift abstracts over types and what each choice costs. Interviewers ask why some View compiles and any is slower.

on this pageshow

explore

questions

17

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, how does a generic function like `largest(in:)` infer `T` at the call site, and why must it constrain `T` to `Comparable`?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Swift fixes T at each call from the argument types, so [Int] makes T Int. The body may use only what the constraints promise, so value > best compiles only after T: Comparable is declared.

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 is the difference between `some PaymentProvider` and `any PaymentProvider` as a parameter type and as a return type?

level: middleimportance: must knowfreq 78%

basics

~20 s

some PaymentProvider stands for one concrete conforming type the compiler tracks: the caller picks it for a parameter, the function picks it for a return. any PaymentProvider is a box whose concrete type can differ from value to value.

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, how does `extension Array where Element: Numeric` add a method only some arrays get, and what error does a `[String]` caller see?

level: middleimportance: should knowfreq 55%

basics

~20 s

A constrained extension declares members that exist only when its where clause holds. [4, 8].total() compiles, while ["tea"].total() fails at compile time with "referencing instance method 'total()' on 'Array' requires that 'String' conform to 'Numeric'".

open as a page

In a Swift generic declaration, what can a `where` clause express that a constraint in the angle brackets cannot, such as a same-type requirement?

level: middleimportance: should knowfreq 50%

basics

~20 s

Angle brackets give each placeholder a single bound: a protocol, composition or superclass. A where clause can also constrain associated types (S.Element: Hashable) and state same-type requirements like S.Element == Key, enforced as exact type identity.

open as a page

In Swift, why does a set of mixed-type idempotency keys need `Set<AnyHashable>` rather than `Set<any Hashable>`?

level: middleimportance: should knowfreq 38%

basics

~20 s

any Hashable is an existential box, and the box does not conform to Hashable, so it cannot be a Set element. AnyHashable is a concrete standard-library struct that conforms to Hashable and forwards equality and hashing to the wrapped value.

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

Inside Swift's `func logKey<T>(_ key: T)`, why does the overloaded call `describeKey(key)` pick the generic overload even when the caller passes an `Int`?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Swift resolves the call once, when it type-checks the generic body, and it uses only T's declared constraints. With an unconstrained T, only describeKey<T>(_:) fits. The Int overload is never a candidate, whatever type the caller passes.

open as a page

In Swift, how do you write a type eraser such as `AnyParser<Output>` by hand, and when does `any Parser<Output>` replace it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

A hand-written eraser is a struct, generic over the associated type, that conforms to the protocol and forwards to a captured base. any Parser<Output> usually suffices unless the value must conform, needs extra conformances, or targets below iOS 16.

open as a page

In Swift, how does passing an `any PaymentProvider` to a generic function let you call members the existential box itself rejects?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Since Swift 5.7 the compiler implicitly opens the box: it binds the function's generic parameter to the value's dynamic type for that call, so members using Self or associated types work inside, and results are erased back to an existential.

open as a page

Why does a Swift factory `func makeParser(format: String) -> some Parser` fail to compile when its branches return different parser types?

level: seniorimportance: should knowfreq 52%

basics

~20 s

An opaque return type stands for exactly one concrete type, which the compiler infers from the body. Returning JSONLinesParser on one path and CSVParser on another gives two underlying types, so Swift rejects the declaration.

open as a page

As the lead of a Swift codebase, what default would you set between `some`, `any` and hand-written type erasure in API signatures, and when would you break it?

level: principalimportance: should knowfreq 36%

basics

~20 s

Default to some or a named generic, which keeps concrete types known to the compiler. Use any where different types must share storage or a dependency is swapped at run time; write an eraser only when the erased value must conform.

open as a page

How does a Swift logging helper declared `func logValues<each Value: CustomStringConvertible>(_ values: repeat each Value)` differ from one taking `Any...`?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

each Value declares a type parameter pack. Every argument keeps its own static type, every one must meet the constraint, and repeat expands code per element. Any... erases every argument to Any inside an array and checks nothing at compile time.

open as a page