Bird
Raised Fist0
Swiftprogramming~10 mins

Adding initializers via extension in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Adding initializers via extension
Define original struct/class
↓
Create extension block
↓
Add new initializer inside extension
↓
Use new initializer to create instance
↓
Instance created with extended initializer
You start with a struct or class, then add an extension where you define a new initializer, and finally use that initializer to create an instance.
Execution Sample
Swift
struct Point {
    var x: Int
    var y: Int
}

extension Point {
    init() {
        self.x = 0
        self.y = 0
    }
}

let origin = Point()
This code adds a new initializer to Point via extension that sets x and y to zero, then creates a Point instance using it.
Execution Table
StepActionEvaluationResult
1Define struct Point with x and yPoint has properties x:Int, y:IntPoint type ready
2Create extension for PointExtension block openedExtension ready to add members
3Add init() initializer in extensioninit() sets x=0, y=0New initializer added
4Call Point() to create originCalls new init()origin.x=0, origin.y=0
5Use origin instanceorigin has x=0, y=0Instance created successfully
💡 All steps complete, instance created using extension initializer
Variable Tracker
VariableStartAfter Step 4Final
origin.xundefined00
origin.yundefined00
Key Moments - 2 Insights
Why can we add an initializer in an extension instead of inside the original struct?
Extensions let us add new initializers without changing the original code, as shown in step 3 of the execution_table.
Does the new initializer replace the default initializer?
No, the new initializer is added alongside existing ones. The code calls the new init() in step 4, not replacing others.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what values does origin have after step 4?
Aorigin.x = 0, origin.y = 0
Borigin.x = undefined, origin.y = undefined
Corigin.x = 1, origin.y = 1
Dorigin.x = nil, origin.y = nil
💡 Hint
Check the 'Result' column in step 4 of execution_table
At which step is the new initializer added to Point?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing adding init() in execution_table
If we remove the extension, what happens when calling Point()?
AIt uses the initializer from extension anyway
BIt fails because no initializer is defined
CIt still works with default initializer
DIt creates an instance with x and y as nil
💡 Hint
Remember Swift structs have a default memberwise initializer unless overridden
Concept Snapshot
struct MyType { var a: Int }
extension MyType {
  init() { self.a = 0 }
}
Use extension to add initializers without changing original code.
Call new init() to create instances with custom defaults.
Full Transcript
We start by defining a struct Point with two properties x and y. Then, we create an extension to add a new initializer that sets both x and y to zero. When we call Point() using this new initializer, it creates an instance with x=0 and y=0. This shows how extensions let us add initializers without modifying the original struct. The execution table traces each step from defining the struct, adding the extension and initializer, to creating an instance. The variable tracker shows origin.x and origin.y changing from undefined to 0 after initialization. Common confusions include why we can add initializers in extensions and whether the new initializer replaces existing ones. The visual quiz tests understanding of values after initialization, when the initializer is added, and what happens if the extension is removed.

Practice

(1/5)
1. What is the main purpose of adding initializers via extension in Swift?
easy
A. To convert a class into a struct
B. To override existing initializers in the original type
C. To delete initializers from the original type
D. To add new ways to create instances without modifying the original type code

Solution

  1. Step 1: Understand what extensions do

    Extensions allow adding new features to existing types without changing their original code.
  2. Step 2: Focus on initializers added via extensions

    Adding initializers via extension means creating new ways to make instances without touching the original type's code.
  3. Final Answer:

    To add new ways to create instances without modifying the original type code -> Option D
  4. Quick Check:

    Extensions add features = A [OK]
Hint: Extensions add, not change original initializers [OK]
Common Mistakes:
  • Thinking extensions override existing initializers
  • Believing extensions remove initializers
  • Confusing extensions with type conversion
2. Which of the following is the correct syntax to add a new initializer to a struct Point via extension?
easy
A. extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } }
B. extension Point { func init(x: Int, y: Int) { self.x = x; self.y = y } }
C. extension Point { init Point(x: Int, y: Int) { self.x = x; self.y = y } }
D. extension Point { initializer(x: Int, y: Int) { self.x = x; self.y = y } }

Solution

  1. Step 1: Recall initializer syntax in extensions

    Initializers use the keyword init without a function keyword.
  2. Step 2: Check each option's syntax

    extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } correctly uses init with parameters and assigns properties. Others misuse keywords like func, add extra words, or wrong keywords.
  3. Final Answer:

    extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } -> Option A
  4. Quick Check:

    Use init keyword only for initializers [OK]
Hint: Initializers use 'init', not 'func' or 'initializer' [OK]
Common Mistakes:
  • Using 'func' instead of 'init' for initializers
  • Adding extra words like 'initializer' or type name after 'init'
  • Incorrect punctuation or missing braces
3. Given the code below, what will be printed?
struct Rectangle {
    var width: Int
    var height: Int
}

extension Rectangle {
    init(size: Int) {
        self.width = size
        self.height = size
    }
}

let square = Rectangle(size: 5)
print(square.width, square.height)
medium
A. 5 0
B. 0 0
C. 5 5
D. Compilation error

Solution

  1. Step 1: Understand the extension initializer

    The extension adds an initializer that sets both width and height to the same size value.
  2. Step 2: Analyze the instance creation and print

    Creating square with size: 5 sets width and height to 5. Printing outputs "5 5".
  3. Final Answer:

    5 5 -> Option C
  4. Quick Check:

    Extension init sets both properties = 5 5 [OK]
Hint: Extension init sets all properties explicitly [OK]
Common Mistakes:
  • Assuming default values instead of assigned ones
  • Expecting compilation error due to missing original initializer
  • Confusing property values after init
4. What is wrong with this extension adding an initializer to a class Car?
class Car {
    var model: String
    init(model: String) {
        self.model = model
    }
}

extension Car {
    init() {
        model = "Unknown"
    }
}
medium
A. Missing call to designated initializer in extension initializer
B. Cannot add initializers to classes via extensions
C. Property model is not declared
D. Extension initializer must have parameters

Solution

  1. Step 1: Recall rules for class initializers in extensions

    When adding a convenience initializer in an extension, it must call a designated initializer of the class.
  2. Step 2: Check the extension initializer code

    The extension initializer sets model directly but does not call self.init(model:), violating the rule.
  3. Final Answer:

    Missing call to designated initializer in extension initializer -> Option A
  4. Quick Check:

    Class extension init must call designated init [OK]
Hint: Class extension init must call self.init(...) [OK]
Common Mistakes:
  • Forgetting to call designated initializer in class extension
  • Thinking extensions can't add initializers to classes
  • Assuming properties auto-initialize without init call
5. You want to add an initializer to a struct User via extension that accepts a dictionary [String: String] and sets name and email. Which code correctly implements this, handling missing keys by setting empty strings?
hard
A. extension User { init(data: [String: String]) { self.name = data["name"]! self.email = data["email"]! } }
B. extension User { init(data: [String: String]) { self.name = data["name"] ?? "" self.email = data["email"] ?? "" } }
C. extension User { init(data: [String: String]) { self.name = data["name"] self.email = data["email"] } }
D. extension User { init(data: [String: String]) { name = data["name"] ?? "" email = data["email"] ?? "" } }

Solution

  1. Step 1: Understand safe unwrapping of dictionary values

    Using ?? "" provides a default empty string if the key is missing, avoiding runtime errors.
  2. Step 2: Check property assignment and self usage

    extension User { init(data: [String: String]) { self.name = data["name"] ?? "" self.email = data["email"] ?? "" } } correctly uses self.name and self.email with safe unwrapping. extension User { init(data: [String: String]) { name = data["name"] ?? "" email = data["email"] ?? "" } } misses self. which is required in initializers.
  3. Final Answer:

    extension User { init(data: [String: String]) { self.name = data["name"] ?? "" self.email = data["email"] ?? "" } } -> Option B
  4. Quick Check:

    Use self and safe default values in init [OK]
Hint: Use 'self.' and '??' for safe dictionary access [OK]
Common Mistakes:
  • Force unwrapping dictionary values causing crashes
  • Omitting 'self.' when assigning properties in init
  • Not providing default values for missing keys
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