skip to content

In Swift, what is a failable initializer, how do you write init? that rejects a bad server payload, and what does the caller get back?

level: juniorimportance: should knowfreq 50%

answer

  1. a question mark after init
  2. return nil on bad input
  3. the result is an Optional
  4. delegation and override limits

basics

~20 s

A failable initializer, written init?, may fail: it executes return nil on bad input and otherwise initializes normally. The caller receives an Optional, User? for User(payload:), and unwraps it with if let or guard let.

solid answer

~40 s

A failable initializer is declared `init?` and is allowed to fail. Inside it, `return nil` signals failure; on success it just initializes every property, with no `return` value. The expression `User(payload: dict)` then has type `User?`, so the caller unwraps it with `if let`, `guard let` or `??`. A typical body uses `guard let id = payload["id"], !id.isEmpty else { return nil }`. Rules worth knowing: a failable and a non-failable initializer cannot share the same parameter labels and types (`invalid redeclaration`); a non-failable initializer cannot delegate to a failable one unless it force-unwraps the call; a subclass may override a failable initializer with a non-failable one, but not the reverse. `init!` is the variant whose result is an implicitly unwrapped Optional.

code

swift · 16 lines
swift
struct User {
    let id: String
    var name: String

    init?(payload: [String: String]) {
        guard let id = payload["id"], !id.isEmpty else { return nil }
        self.id = id
        self.name = payload["name"] ?? "Guest"
    }
}

let missing = User(payload: ["name": "Ana"])   // nil: no "id"
if let user = User(payload: ["id": "7"]) {
    print(user.name)                           // Guest
}
print(missing == nil)                          // true

go deeper

for a junior

Recall the init? syntax, that return nil means failure, and that the caller receives an Optional to unwrap.

for a middle

Explain the delegation rules between failable and non-failable initializers, the overriding direction, and what init! changes for the caller.

for a senior

Choose between init?, init! and a throwing initializer for a payload type, and spot a force-unwrapped delegation that can trap at run time.

for a principal

Settle how model types report invalid input across a codebase, so callers handle Optional results and thrown errors consistently.

## What makes an initializer failable Some inputs simply cannot produce a valid value: a server payload with no `id`, an empty name, a malformed string. A **failable initializer** expresses that in the type system. You write a question mark after `init`: ```swift init?(payload: [String: String]) { guard let id = payload["id"], !id.isEmpty else { return nil } self.id = id self.name = payload["name"] ?? "Guest" } ``` Key points about the body: - **`return nil`** is how the initializer fails. It can appear anywhere, including before all stored properties have values. - On success the initializer **returns nothing**: it just finishes assigning properties, like any other initializer. - The result of calling it is an **Optional** of the type: `User(payload: dict)` has type `User?`. ## Using the result Because the result is `User?`, the caller has to deal with failure: 1. `if let user = User(payload: dict) { ... }` to act only on success; 2. `guard let user = User(payload: dict) else { return }` to exit early; 3. `User(payload: dict) ?? .guest` to fall back to a default value. The Optional carries **no reason** for the failure. When the caller needs to know *why* the payload was rejected (missing key versus bad format), a throwing initializer is the usual alternative; choosing between Optional and thrown errors is covered in the lessons on error handling. Swift also synthesizes failable initializers for you in one familiar place: an enum with raw values gets `init?(rawValue:)`, covered with enum raw values. ## Rules the compiler enforces | Situation | Allowed? | What Swift 6.4 says | |---|---|---| | `init?(id:)` and `init(id:)` in one type | No | `invalid redeclaration of 'init(id:)'` | | failable delegates to non-failable | Yes | — | | failable delegates to failable | Yes; failure propagates and the rest of the body does not run | — | | non-failable delegates to failable | Only with `!` on the call | `a non-failable initializer cannot delegate to failable initializer 'init(id:)' written with 'init?'` | | subclass overrides failable with non-failable | Yes, force-unwrapping `super.init(...)` if needed | — | | subclass overrides non-failable with failable | No | `failable initializer 'init(name:)' cannot override a non-failable initializer` | The override direction follows from substitutability: code holding a `Shape` initializer that never fails must not suddenly get one that can. ## Failable initializers in classes Classes follow the same two-phase rules as any other initializer, with one relaxation: **`return nil` may come before** the class has initialized its stored properties or called `super.init`. A `Circle` can reject a non-positive radius on its first line. When a subclass overrides a failable superclass initializer with a non-failable one, it must avoid the failing input and force-unwrap the result of `super.init(...)`; the second example passes a fallback name for exactly that reason. ## The init! variant `init!` declares a failable initializer whose result is an **implicitly unwrapped Optional**, `User!`. You can assign it to a non-optional `User` without unwrapping, but if it failed, that use traps at run time. It exists mostly for imported APIs. You can delegate between `init?` and `init!` in either direction, and override one with the other. ## When to choose a failable initializer - **Parsing and validation where the reason does not matter**: building a `User` from a dictionary, a value type from a string, a wrapper that only accepts non-empty input. - **Not** when callers must report why the input was rejected; a throwing initializer carries that information. - **Prefer `init?` over `init!`** in new code: `init!` hides the failure check at the call site and turns a bad payload into a trap far from where it was created. The caller-facing contract is the type itself: a `User?` result tells every caller, at compile time, that construction can fail. ## Common mistakes - Writing `return self` or `return User(...)` on success: initializers do not return values. - Assuming failure throws or crashes: the caller simply gets `nil`. - Writing a failable `init?(id:)` beside a non-failable `init(id:)` and expecting overload resolution to pick one: the compiler rejects the pair.

  • Can a non-failable initializer call a failable one in the same struct?
    Only by force-unwrapping the delegation, as in `self.init(id: raw)!`, which traps at run time if it fails. Without the `!`, Swift 6.4 reports `a non-failable initializer cannot delegate to failable initializer 'init(id:)' written with 'init?'`.
  • Why can a subclass override init? with init but not the other way round?
    Code that calls the superclass's non-failable initializer relies on getting an instance. A failable override would break that promise, so the compiler reports `failable initializer 'init(name:)' cannot override a non-failable initializer`. Narrowing a failable initializer to one that always succeeds keeps every caller correct.

  • A failable initializer signals failure by throwing an error.
  • A successful failable initializer must end with return self.
  • Swift lets you overload init?(id:) and init(id:) with the same parameters.
  • A subclass may override a non-failable initializer with a failable one.
  • The caller of init? receives a non-optional value that is nil-checked automatically.