← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 8 of 9

Initializers

An initializer is the special setup code that runs when you create a new instance, making sure everything starts with proper values.

Custom Initializer

A custom init lets you control exactly how an instance's stored properties are set, including validation logic.

Example: Custom Initializer

markup
struct Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = max(0, age)
    }
}
let person = Person(name: "Alex", age: -5)
print("\(person.name) is \(person.age) years old")

Failable Initializers

An init? initializer can return nil when the given input isn't valid, which is common when parsing or validating data.

Example: Failable Initializers

markup
struct PositiveNumber {
    let value: Int
    init?(value: Int) {
        guard value > 0 else { return nil }
        self.value = value
    }
}
let good = PositiveNumber(value: 5)
let bad = PositiveNumber(value: -3)
print(good?.value as Any)
print(bad?.value as Any)
Common Mistakes
  1. Forgetting that a class initializer must set every non-optional stored property before calling any method or returning.
  2. Writing a custom initializer on a struct and being surprised the automatic memberwise initializer is no longer available unless declared in an extension.
  3. Confusing a failable initializer (init?) which can return nil, with a regular initializer that always succeeds.
Chapter Summary
  • init defines how an instance is created and its stored properties set up.
  • Structs lose their automatic memberwise initializer once you write a custom init directly in the struct body.
  • A failable initializer, written as init?, can return nil if setup fails.
  • Every stored property must have a value by the end of initialization.
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.