Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 146 ยท Structures, Classes and Enums

Initializers

Learn Swift initializers - memberwise and custom init, default values, failable init?, designated and convenience initializers, required init and two-phase initialization with real errors.

Before you can use a value, Swift insists that every one of its stored properties has a value. An initializer is the code that makes this true. It is the init you call whenever you write User(name: "Ada"), and it is how Swift prevents an entire family of bugs: you can never get a half-built object with garbage in its fields.

This lesson starts with the initializer you get for free, then writes your own, adds validation with failable initializers, and finishes with the rules for classes: designated and convenience initializers, required, and the two-phase process that makes inheritance safe.

Default values and memberwise initializers

If every stored property has a default value, you can create an instance with plain Type(). For a struct, Swift also synthesizes a memberwise initializer that has one parameter per stored property, in declaration order.

Swift Free initializers for structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Properties with defaults make their parameter optional, so you can leave out fontSize but still set showLineNumbers if you keep the order. Classes do not get a memberwise initializer; they only get init() when all properties have defaults.

Writing your own init

An init has no func keyword and no return type. Its job is to give every stored property a value. Use self.name = name when a parameter shares a property's name.

Swift A custom initializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You can define as many initializers as you like, as long as their signatures (labels and types) differ. The argument labels are part of the call, which makes Temperature(fahrenheit: 212) self-documenting.

If you write any custom init inside the struct body, Swift stops giving you the memberwise initializer. To keep both, put your custom initializers in an extension; the compiler still generates the memberwise one for the original declaration.

Swift Keeping the memberwise init with an extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice self.init(...). In a value type, an initializer may delegate to another initializer, which avoids repeating logic.

Forgetting a property

The compiler checks that every path through init sets every stored property.

Swift An unset property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message reads return from initializer without initializing all stored properties, with a note that 'self.email' not initialized. The fix is to assign it, give it a default, or make it optional (var email: String?, which defaults to nil).

Failable initializers

Sometimes the inputs can be invalid: a negative age, an empty name, a string that is not a number. A failable initializer, written init?, may return nil to say "I could not build that". The result is an optional.

Swift init? returns nil for bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Many standard types use failable initializers: Int("42") returns nil for text that is not a number. Enums with raw values get one automatically (Direction(rawValue: "up")). Unwrap the result with if let or guard let, as in Optionals.

When failure should carry an explanation, a throwing initializer (init(...) throws) is the better design because the caller learns why. See Errors.

Classes: designated and convenience initializers

Classes have two flavors of initializer:

  • A designated initializer is the main one. It must initialize all the class's own stored properties and then call up to a superclass initializer (if there is a superclass).
  • A convenience initializer (convenience init) is a shortcut. It must call another initializer of the same class, eventually reaching a designated one.
Swift Designated and convenience initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The rule of thumb: delegate across (convenience calls another initializer of the same class) and delegate up (designated calls the superclass). Keep the minimum number of designated initializers and let convenience ones supply defaults.

Two-phase initialization

Swift builds class instances in two phases, and it enforces the order:

  1. Phase 1: every stored property, starting with the subclass and moving up through each superclass, gets a value. You cannot use self yet (no calling methods, no reading inherited properties).
  2. Phase 2: after the superclass init returns, the instance is fully formed. Now you may use self, call methods and customize inherited properties.
Swift Subclass initializer with both phases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

If you swap the order and use self.name before super.init, the compiler refuses. Try it on your own: the error is 'self' used in property access 'name' before 'super.init' call. This safety net guarantees that no method ever runs on a partially built object.

Inheriting initializers

A subclass that defines its own designated initializers does not inherit the superclass's. If it defines none and gives defaults to all new properties, it inherits them all. This is why a plain class Dog: Animal {} with no new stored properties just works with Dog(name:).

required initializers

Mark an initializer required to force every subclass to provide it (by implementing it, or by inheriting it). Frameworks use this for things like creating an object from stored data.

Swift required init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The generic function can call type.init(sides:) on any Shape subclass because required guarantees every subclass has it. Without required, the compiler would not allow that call.

Setting a property with a closure

A default value may be computed by a closure that runs once, during initialization. This is handy for configuring a value inline.

Swift Default values from a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Note the () at the end: you store the closure's result, not the closure. The closure cannot use self or other properties, because the instance is not ready yet.

Choosing your design

  • Prefer a struct and the free memberwise initializer when the type is plain data.
  • Use default values to cut the number of initializers you need.
  • Use init? when invalid input is normal, init throws when callers need a reason, and precondition for programmer errors.
  • Give classes few designated initializers and several convenience ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a struct's free memberwise initializer if you write a custom init inside the struct body?

    Adding an initializer in the main body removes the memberwise one. Initializers declared in an extension do not.
  2. 2. What is the type of the result of calling a failable initializer such as Int("7")?

    A failable initializer returns an optional: the value on success, nil on failure.
  3. 3. In two-phase initialization, what must a subclass designated initializer do first?

    Phase 1 gives every stored property a value, subclass properties first. Only after super.init returns can you use self.
  4. 4. What must a convenience initializer do?

    Convenience initializers delegate across to another initializer in the same class, eventually reaching a designated one.
  5. 5. What does required on an initializer guarantee?

    required forces every subclass to implement or inherit the initializer.

Summary

  • An initializer must give every stored property a value before the instance is used.
  • Structs get a memberwise initializer for free; custom init in the body removes it, an extension does not.
  • init? returns nil for invalid input; init throws explains why.
  • Class designated initializers set their own properties, then call super.init; convenience initializers delegate within the class.
  • Two-phase initialization forbids using self before every property has a value.
  • required forces subclasses to provide an initializer.
  • A closure with () can build a property's default value.

Next: Memory Management with ARC