Initializers
An initializer is the special setup code that runs when you create a new instance, making sure everything starts with proper values.
In this page:
Custom Initializer
A custom init lets you control exactly how an instance's stored properties are set, including validation logic.
Example: Custom Initializer
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = max(0, age)
}
}
let person = Person(name: "Alex", age: -5)
print("\(person.name) is \(person.age) years old")
Login to try C/C++/Java/PHP code in the editor
Failable Initializers
An init? initializer can return nil when the given input isn't valid, which is common when parsing or validating data.
Example: Failable Initializers
struct PositiveNumber {
let value: Int
init?(value: Int) {
guard value > 0 else { return nil }
self.value = value
}
}
let good = PositiveNumber(value: 5)
let bad = PositiveNumber(value: -3)
print(good?.value as Any)
print(bad?.value as Any)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that a class initializer must set every non-optional stored property before calling any method or returning.
- Writing a custom initializer on a struct and being surprised the automatic memberwise initializer is no longer available unless declared in an extension.
- Confusing a failable initializer (
init?) which can returnnil, with a regular initializer that always succeeds.
Chapter Summary
initdefines how an instance is created and its stored properties set up.- Structs lose their automatic memberwise initializer once you write a custom
initdirectly in the struct body. - A failable initializer, written as
init?, can returnnilif setup fails. - Every stored property must have a value by the end of initialization.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: