Bird
Raised Fist0
Swiftprogramming~10 mins

Convenience initializers in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Convenience initializers
Call Convenience Init
↓
Perform Custom Setup
↓
Call Designated Init
↓
Complete Initialization
↓
Object Ready
A convenience initializer calls another initializer in the same class to reuse setup code, then completes object creation.
Execution Sample
Swift
class Car {
  var color: String
  var model: String

  init(model: String, color: String) {
    self.model = model
    self.color = color
  }

  convenience init(model: String) {
    self.init(model: model, color: "Black")
  }
}

let car = Car(model: "Sedan")
Creates a Car object using a convenience initializer that sets a default color.
Execution Table
StepActionEvaluationResult
1Call convenience init with model="Sedan"convenience init(model: String)Starts convenience initializer
2Inside convenience init, call designated init with model="Sedan", color="Black"self.init(model: model, color: "Black")Calls designated initializer
3Designated init sets self.model = "Sedan"self.model = modelmodel property set to "Sedan"
4Designated init sets self.color = "Black"self.color = colorcolor property set to "Black"
5Designated init completesinit completeObject properties initialized
6Convenience init completesconvenience init completeObject ready for use
💡 Initialization ends after convenience initializer calls designated initializer and completes.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
modelnil"Sedan""Sedan""Sedan"
colornilnil"Black""Black"
Key Moments - 2 Insights
Why does the convenience initializer call the designated initializer?
Because in Swift, convenience initializers must call a designated initializer to ensure all properties are properly initialized, as shown in step 2 of the execution_table.
Can a convenience initializer set properties directly without calling another initializer?
No, convenience initializers cannot set all properties directly; they must call a designated initializer first, which sets the properties, as seen in steps 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'color' after step 4?
A"Sedan"
B"Black"
Cnil
D"Red"
💡 Hint
Check the variable_tracker row for 'color' after step 4.
At which step does the designated initializer complete its work?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Action' column in the execution_table for when 'init complete' happens.
If the convenience initializer did not call the designated initializer, what would happen?
AThe code would not compile because all properties must be initialized.
BThe object would be fully initialized anyway.
CThe convenience initializer would set default values automatically.
DThe designated initializer would be called automatically.
💡 Hint
Recall Swift's rule that convenience initializers must call a designated initializer (see key_moments).
Concept Snapshot
Convenience initializers in Swift:
- Use 'convenience init' keyword
- Must call another initializer in the same class
- Help provide default or simpler ways to create objects
- Cannot fully initialize properties themselves
- Always call a designated initializer to complete setup
Full Transcript
This example shows how a convenience initializer in Swift works. When we create a Car object with only a model, the convenience initializer runs first. It calls the designated initializer with a default color. The designated initializer sets the model and color properties. Then initialization finishes, and the object is ready. Convenience initializers help avoid repeating code by reusing designated initializers. They must call a designated initializer to ensure all properties are set properly. This flow ensures safe and complete object creation.

Practice

(1/5)
1. What is the main purpose of a convenience initializer in Swift?
easy
A. To provide an easier way to create an object by calling a designated initializer
B. To override a superclass initializer
C. To create a completely new object without calling any other initializer
D. To deallocate an object before it is destroyed

Solution

  1. Step 1: Understand the role of convenience initializers

    Convenience initializers are shortcuts to create objects more easily by calling a designated initializer.
  2. Step 2: Compare options with this role

    Only To provide an easier way to create an object by calling a designated initializer describes this purpose correctly; others describe unrelated concepts.
  3. Final Answer:

    To provide an easier way to create an object by calling a designated initializer -> Option A
  4. Quick Check:

    Convenience initializer = shortcut calling designated initializer [OK]
Hint: Convenience initializers always call a designated initializer [OK]
Common Mistakes:
  • Thinking convenience initializers create objects independently
  • Confusing convenience initializers with deinitializers
  • Believing convenience initializers override superclass initializers
2. Which of the following is the correct syntax for a convenience initializer in Swift?
easy
A. convenience func init(name: String) { self.init() }
B. init convenience(name: String) { self.init() }
C. func convenience init(name: String) { self.init() }
D. convenience init(name: String) { self.init() }

Solution

  1. Step 1: Recall the correct syntax for convenience initializers

    In Swift, the keyword convenience comes before init without any function keyword.
  2. Step 2: Check each option

    convenience init(name: String) { self.init() } matches the correct syntax. Options B, C, and D misuse keywords or order.
  3. Final Answer:

    convenience init(name: String) { self.init() } -> Option D
  4. Quick Check:

    Keyword order: convenience before init [OK]
Hint: Remember: 'convenience' keyword comes before 'init' [OK]
Common Mistakes:
  • Placing 'convenience' after 'init'
  • Using 'func' keyword with initializers
  • Incorrect keyword order causing syntax errors
3. Consider the following Swift code:
class Car {
    var color: String
    init(color: String) {
        self.color = color
    }
    convenience init() {
        self.init(color: "Red")
    }
}
let myCar = Car()

What is the value of myCar.color?
medium
A. nil
B. "Red"
C. "" (empty string)
D. Compilation error

Solution

  1. Step 1: Understand the initializers in the Car class

    The designated initializer sets the color property. The convenience initializer calls the designated one with "Red".
  2. Step 2: Analyze the object creation

    Creating myCar with Car() calls the convenience initializer, which sets color to "Red".
  3. Final Answer:

    "Red" -> Option B
  4. Quick Check:

    Convenience init sets color to "Red" [OK]
Hint: Convenience init calls designated init with default values [OK]
Common Mistakes:
  • Assuming color is empty or nil without initialization
  • Thinking convenience init does not call designated init
  • Expecting compilation error due to missing default init
4. Identify the error in this Swift class using a convenience initializer:
class Person {
    var name: String
    convenience init() {
        self.name = "Unknown"
    }
    init(name: String) {
        self.name = name
    }
}
medium
A. Convenience initializer must call a designated initializer, not assign properties directly
B. Designated initializer must be marked as convenience
C. Property 'name' must be optional
D. No error, code is correct

Solution

  1. Step 1: Recall rules for convenience initializers

    A convenience initializer must call another initializer in the same class, not assign properties directly.
  2. Step 2: Check the convenience init implementation

    Here, self.name = "Unknown" is assigned directly, which is not allowed.
  3. Final Answer:

    Convenience initializer must call a designated initializer, not assign properties directly -> Option A
  4. Quick Check:

    Convenience init must call designated init [OK]
Hint: Convenience init cannot set properties directly; must call designated init [OK]
Common Mistakes:
  • Assigning properties directly in convenience initializer
  • Marking designated initializer as convenience
  • Making properties optional unnecessarily
5. You want to create a Swift class Rectangle with a designated initializer that takes width and height, and a convenience initializer that creates a square by taking only one side length. Which of the following implementations correctly uses a convenience initializer?
hard
A. class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(side: Double) { self.width = side self.height = side } }
B. class Rectangle { var width: Double var height: Double convenience init(width: Double, height: Double) { self.width = width self.height = height } init(side: Double) { self.width = side self.height = side } }
C. class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(side: Double) { self.init(width: side, height: side) } }
D. class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(side: Double) { self.height = side } }

Solution

  1. Step 1: Identify designated and convenience initializers

    The designated initializer takes width and height. The convenience initializer should call the designated one.
  2. Step 2: Check each option for correct usage

    class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(side: Double) { self.init(width: side, height: side) } } correctly defines the designated init and the convenience init calls it with equal sides. Others either misuse convenience keyword or assign properties directly.
  3. Final Answer:

    class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } convenience init(side: Double) { self.init(width: side, height: side) } } -> Option C
  4. Quick Check:

    Convenience init calls designated init with side values [OK]
Hint: Convenience init must call designated init with all required parameters [OK]
Common Mistakes:
  • Marking designated initializer as convenience
  • Assigning properties directly in convenience initializer
  • Not calling designated initializer from convenience initializer
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