Bird
Raised Fist0
Swiftprogramming~3 mins

Why Adding initializers via extension in Swift? - Purpose & Use Cases

Choose your learning style10 modes available
The Big Idea

What if you could add new ways to create objects without ever touching the original code?

The Scenario

Imagine you have a Swift struct or class, and you want to create new ways to make instances of it. Without extensions, you have to change the original code every time you want a new initializer.

The Problem

This manual way is slow and risky. Changing original code can cause bugs, and if the code is from a library, you can't change it at all. You end up repeating code or making messy workarounds.

The Solution

Adding initializers via extension lets you add new ways to create instances without touching the original code. It keeps your code clean, safe, and flexible.

Before vs After
✗ Before
struct Person {
    var name: String
    var age: Int
    
    init(name: String) {
        self.name = name
        self.age = 0
    }
}
✓ After
struct Person {
    var name: String
    var age: Int
}

extension Person {
    init(name: String) {
        self.init(name: name, age: 0)
    }
}
What It Enables

You can easily add new initializers anytime, even for types you don't own, making your code more powerful and adaptable.

Real Life Example

Suppose you use a library with a Date type. You want to create a Date from a string. You can add an initializer in an extension to do this without changing the library code.

Key Takeaways

Adding initializers via extension avoids changing original code.

It keeps your code clean and safe from bugs.

It allows flexible ways to create instances anytime.

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