Bird
Raised Fist0
Swiftprogramming~20 mins

Adding initializers via extension in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Initializer Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of initializer added via extension
What is the output of this Swift code that adds an initializer via extension?
Swift
struct Point {
    var x: Int
    var y: Int
}

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

let p = Point()
print("(\(p.x), \(p.y))")
A(x: 0, y: 0)
B(nil, nil)
CCompilation error
D(0, 0)
Attempts:
2 left
💡 Hint
Think about what the extension initializer sets the properties to.
❓ Predict Output
intermediate
2:00remaining
Value of property after extension initializer
What is the value of the property 'name' after creating an instance using the extension initializer?
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

extension Person {
    convenience init() {
        self.init(name: "Unknown")
    }
}

let p = Person()
print(p.name)
AEmpty string
Bnil
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Check what the convenience initializer passes to the designated initializer.
🔧 Debug
advanced
2:00remaining
Why does this extension initializer cause a compile error?
Consider this Swift code. Why does the extension initializer cause a compile error?
Swift
struct Rectangle {
    var width: Int
    var height: Int
}

extension Rectangle {
    init(area: Int) {
        self.width = area
        // Missing height initialization
    }
}
AAll stored properties must be initialized before use, height is missing.
BExtensions cannot add initializers to structs.
CThe init method must be marked as convenience.
DThe code is valid and compiles without errors.
Attempts:
2 left
💡 Hint
Check if all stored properties are initialized in the initializer.
📝 Syntax
advanced
2:00remaining
Which extension initializer syntax is correct?
Which of the following extension initializers for struct Circle is syntactically correct?
Swift
struct Circle {
    var radius: Double
}

// Choose the correct extension initializer syntax:
A
extension Circle {
    init(diameter: Double) {
        self.radius = diameter / 2
    }
}
B
extension Circle {
    convenience init(diameter: Double) {
        self.radius = diameter / 2
    }
}
C
extension Circle {
    init(diameter: Double) {
        radius = diameter / 2
    }
}
D
extension Circle {
    convenience init(diameter: Double) {
        radius = diameter / 2
    }
}
Attempts:
2 left
💡 Hint
Remember that convenience initializers are only for classes, not structs.
🚀 Application
expert
2:00remaining
How many initializers does this class have after extension?
Given this Swift class and its extension, how many initializers does the class have in total?
Swift
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
}

extension Vehicle {
    convenience init() {
        self.init(wheels: 4)
    }
}
A1
B2
C3
D0
Attempts:
2 left
💡 Hint
Count both the original and extension initializers.

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