What if you could create complex objects in one simple step without missing anything?
Why Initializers and designated init in Swift? - Purpose & Use Cases
Imagine you want to create a new object in your app, like a user profile, and you have to set up all the details manually every time. You write code to assign each property one by one, repeating this for every new user.
This manual way is slow and easy to mess up. You might forget to set a property or assign wrong values. It makes your code long, confusing, and hard to maintain, especially when your objects get more complex.
Initializers, especially designated initializers, let you set up all necessary properties in one clean step. They ensure your object is ready to use right after creation, reducing mistakes and making your code simpler and safer.
var user = User() user.name = "Alice" user.age = 30 user.email = "alice@example.com"
let user = User(name: "Alice", age: 30, email: "alice@example.com")
It lets you create fully prepared objects quickly and reliably, making your app more stable and your code easier to read.
Think of setting up a new contact in your phone app: instead of typing each detail separately every time, you fill a form once and save it. Initializers do the same for your code objects.
Manual property setting is slow and error-prone.
Designated initializers set all needed properties at once.
This leads to safer, cleaner, and easier-to-maintain code.
Practice
Solution
Step 1: Understand what initializers do
Initializers set starting values for new objects to ensure they are ready to use.Step 2: Identify the role of designated initializers
Designated initializers fully initialize all properties of a class, making the object safe and complete.Final Answer:
To fully initialize all properties of a class before use -> Option AQuick Check:
Designated initializer = full property initialization [OK]
- Confusing designated init with convenience init
- Thinking initializers copy objects
- Mixing initialization with deallocation
Solution
Step 1: Recall Swift initializer syntax
In Swift, initializers use the keywordinitwithout a return type or func keyword.Step 2: Identify the correct syntax
The correct syntax isinit() { }. Other options use incorrect keywords or syntax.Final Answer:
init() { } -> Option BQuick Check:
Swift designated init syntax = init() { } [OK]
- Using 'func' keyword with init
- Using 'constructor' or 'initialize' instead of 'init'
- Adding return types to init
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")?Solution
Step 1: Analyze the initializer code
The initializer setsself.name = nameand explicitly setsself.age = 0.Step 2: Determine the value of age after initialization
Sinceageis set to 0 inside the initializer, the new object will haveage = 0.Final Answer:
0 -> Option DQuick Check:
Explicit age assignment = 0 [OK]
- Assuming age is nil because not passed as parameter
- Thinking age is uninitialized or undefined
- Confusing name with age value
class Car {
var model: String
var year: Int
init(model: String) {
model = model
year = 2020
}
}Solution
Step 1: Check property assignments in initializer
The code assignsmodel = modelandyear = 2020withoutself., so it assigns parameters to themselves, not properties.Step 2: Understand correct property initialization
Properties must be assigned withself.model = modelandself.year = 2020to set the instance variables.Final Answer:
Properties are not initialized using self keyword -> Option CQuick Check:
Use self.property = value to initialize [OK]
- Forgetting self. causes no property assignment
- Adding return type to init
- Thinking inheritance affects property assignment
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?Solution
Step 1: Understand default parameter values in Swift
Swift allows default values in parameters, sopages: Int = 100means pages defaults to 100 if not passed.Step 2: Check initializer completeness and safety
The initializerinit(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 atitleparameter cannot setpagesexplicitly. The version taking both parameters but only assigningtitlemisses thepagesassignment. The version using an optionalInt?for pages with force unwrap is unsafe.Final Answer:
init(title: String, pages: Int = 100) { self.title = title; self.pages = pages } -> Option AQuick Check:
Default parameter = safe default value [OK]
- Forgetting to assign all properties
- Using force unwrap (!) unsafely
- Not providing default value in parameter
Ready to prove it?
Pass the test and this pattern moves unknown
