Bird
Raised Fist0
Swiftprogramming~10 mins

Initializers and designated init in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Initializers and designated init
Start: Create instance
↓
Call designated init
↓
Initialize all properties
↓
Call superclass init if subclass
↓
Instance ready to use
↓
End
The flow shows how a designated initializer sets up all properties and calls superclass initializers if needed, preparing the instance for use.
Execution Sample
Swift
class Person {
  var name: String
  init(name: String) {
    self.name = name
  }
}

let p = Person(name: "Anna")
This code creates a Person instance by calling its designated initializer to set the name property.
Execution Table
StepActionProperty 'name' ValueInstance State
1Call Person.init(name: "Anna")uninitializedInstance created, properties uninitialized
2Assign self.name = "Anna"AnnaProperty 'name' initialized
3Initializer completesAnnaInstance ready to use
4Return instance to callerAnnaInstance assigned to variable p
💡 Initialization completes after all properties are set and initializer returns
Variable Tracker
VariableStartAfter Step 2Final
self.nameuninitializedAnnaAnna
pnilnilPerson instance with name 'Anna'
Key Moments - 2 Insights
Why must all properties be initialized before the initializer ends?
Because Swift requires all stored properties to have a value before the instance is used, as shown in step 3 of the execution_table where 'name' is set before completion.
What is a designated initializer?
It is the main initializer that fully initializes all properties and calls superclass initializers if needed, as shown in step 1 where Person.init is called.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'self.name' after step 1?
Aempty string
B"Anna"
Cuninitialized
Dnil
💡 Hint
Check the 'Property 'name' Value' column at step 1 in execution_table
At which step does the instance become ready to use?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Instance State' column in execution_table for when initialization completes
If the property 'name' was not assigned, what would happen?
AThe initializer would complete successfully
BThe compiler would give an error
CThe instance would have a default name
DThe instance would be nil
💡 Hint
Swift requires all properties to be initialized before initializer ends, see key_moments explanation
Concept Snapshot
class MyClass {
  var prop: Type
  init(prop: Type) {
    self.prop = prop  // Designated init sets all properties
  }
}
- Designated init fully initializes all stored properties
- Must call superclass init if subclass
- Instance ready after init completes
Full Transcript
This visual trace shows how Swift's designated initializer works. When creating an instance, the designated initializer is called first. It sets all stored properties, like 'name' in the example. Only after all properties are initialized does the initializer complete and the instance becomes ready to use. This ensures safe and predictable object creation. If any property is not set, Swift will give a compile-time error. The flow also includes calling superclass initializers if the class inherits from another. This step-by-step trace helps beginners see how initialization happens internally.

Practice

(1/5)
1. What is the main purpose of a designated initializer in Swift?
easy
A. To fully initialize all properties of a class before use
B. To provide default values for optional properties only
C. To create a copy of an existing object
D. To deallocate memory when an object is no longer needed

Solution

  1. Step 1: Understand what initializers do

    Initializers set starting values for new objects to ensure they are ready to use.
  2. Step 2: Identify the role of designated initializers

    Designated initializers fully initialize all properties of a class, making the object safe and complete.
  3. Final Answer:

    To fully initialize all properties of a class before use -> Option A
  4. Quick Check:

    Designated initializer = full property initialization [OK]
Hint: Designated init always sets all properties fully [OK]
Common Mistakes:
  • Confusing designated init with convenience init
  • Thinking initializers copy objects
  • Mixing initialization with deallocation
2. Which of the following is the correct syntax for a designated initializer in a Swift class?
easy
A. func init() { }
B. init() { }
C. constructor() { }
D. initialize() { }

Solution

  1. Step 1: Recall Swift initializer syntax

    In Swift, initializers use the keyword init without a return type or func keyword.
  2. Step 2: Identify the correct syntax

    The correct syntax is init() { }. Other options use incorrect keywords or syntax.
  3. Final Answer:

    init() { } -> Option B
  4. Quick Check:

    Swift designated init syntax = init() { } [OK]
Hint: Swift init uses just 'init', no func or constructor [OK]
Common Mistakes:
  • Using 'func' keyword with init
  • Using 'constructor' or 'initialize' instead of 'init'
  • Adding return types to init
3. Consider this Swift class:
class Person {
  var name: String
  var age: Int

  init(name: String) {
    self.name = name
    self.age = 0
  }
}
What will be the value of age after creating let p = Person(name: "Anna")?
medium
A. Name of the person
B. nil
C. Undefined
D. 0

Solution

  1. Step 1: Analyze the initializer code

    The initializer sets self.name = name and explicitly sets self.age = 0.
  2. Step 2: Determine the value of age after initialization

    Since age is set to 0 inside the initializer, the new object will have age = 0.
  3. Final Answer:

    0 -> Option D
  4. Quick Check:

    Explicit age assignment = 0 [OK]
Hint: Check initializer assignments for property values [OK]
Common Mistakes:
  • Assuming age is nil because not passed as parameter
  • Thinking age is uninitialized or undefined
  • Confusing name with age value
4. Identify the error in this Swift class initializer:
class Car {
  var model: String
  var year: Int

  init(model: String) {
    model = model
    year = 2020
  }
}
medium
A. Initializer missing return type
B. Class must inherit from NSObject
C. Properties are not initialized using self keyword
D. year property cannot be assigned a value

Solution

  1. Step 1: Check property assignments in initializer

    The code assigns model = model and year = 2020 without self., so it assigns parameters to themselves, not properties.
  2. Step 2: Understand correct property initialization

    Properties must be assigned with self.model = model and self.year = 2020 to set the instance variables.
  3. Final Answer:

    Properties are not initialized using self keyword -> Option C
  4. Quick Check:

    Use self.property = value to initialize [OK]
Hint: Use self. to assign properties inside init [OK]
Common Mistakes:
  • Forgetting self. causes no property assignment
  • Adding return type to init
  • Thinking inheritance affects property assignment
5. You want to create a Swift class Book with properties title (String) and pages (Int). The designated initializer should allow setting both properties, but if pages is not provided, it defaults to 100. Which is the best way to write this initializer?
hard
A. init(title: String, pages: Int = 100) { self.title = title; self.pages = pages }
B. init(title: String) { self.title = title; self.pages = 100 }
C. init(title: String, pages: Int) { self.title = title }
D. init(title: String, pages: Int?) { self.title = title; self.pages = pages! }

Solution

  1. Step 1: Understand default parameter values in Swift

    Swift allows default values in parameters, so pages: Int = 100 means pages defaults to 100 if not passed.
  2. Step 2: Check initializer completeness and safety

    The initializer init(title: String, pages: Int = 100) { self.title = title; self.pages = pages } sets both properties properly and safely with a default value. The version with only a title parameter cannot set pages explicitly. The version taking both parameters but only assigning title misses the pages assignment. The version using an optional Int? for pages with force unwrap is unsafe.
  3. Final Answer:

    init(title: String, pages: Int = 100) { self.title = title; self.pages = pages } -> Option A
  4. Quick Check:

    Default parameter = safe default value [OK]
Hint: Use default parameter values for optional init args [OK]
Common Mistakes:
  • Forgetting to assign all properties
  • Using force unwrap (!) unsafely
  • Not providing default value in parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard