← 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.
Syntax
swift
struct TypeName {
    var property: Type

    init(property: Type) {
        self.property = property
    }

    init?(input: Type) {   // failable: may return nil
        guard condition else { return nil }
        self.property = input
    }
}

Custom Initializer

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

Example: Custom Initializer

markup
// Define a struct `Person`
struct Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = max(0, age)
    }
}
// Declare a constant `person`, set to `Person(name: "Alex", age: -5)`
let person = Person(name: "Alex", age: -5)
// Print "\(person.name) is \(person.age) years old" to the console
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
// Define a struct `PositiveNumber`
struct PositiveNumber {
    let value: Int
    init?(value: Int) {
        guard value > 0 else { return nil }
        self.value = value
    }
}
// Declare a constant `good`, set to `PositiveNumber(value: 5)`
let good = PositiveNumber(value: 5)
// Declare a constant `bad`, set to `PositiveNumber(value: -3)`
let bad = PositiveNumber(value: -3)
// Print `good?.value as Any` to the console
print(good?.value as Any)
// Print `bad?.value as Any` to the console
print(bad?.value as Any)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.