Swift Initializers
Setting up initial values for class and struct instances
🚀 What are Initializers?
Initializers are special methods that prepare new instances of classes, structures, or enumerations for use. They set initial values for stored properties and perform any setup required before the instance is ready.
struct Person {
var name: String
var age: Int
// Designated initializer
init(name: String, age: Int) {
self.name = name
self.age = age
}
// Convenience initializer
init(name: String) {
self.init(name: name, age: 0)
}
}
let person1 = Person(name: "Alice", age: 25)
let person2 = Person(name: "Bob")
print("\(person1.name) is \(person1.age) years old")
Output:
Alice is 25 years old
Types of Initializers
Designated
Primary initializers that fully initialize all properties
init(name: String, age: Int) {
self.name = name
self.age = age
}
Convenience
Secondary initializers that call designated initializers
convenience init(name: String) {
self.init(name: name, age: 0)
}
Failable
Initializers that can return nil if initialization fails
init?(age: Int) {
if age < 0 { return nil }
self.age = age
}
Required
Initializers that must be implemented by subclasses
required init(name: String) {
self.name = name
}
🔹 Basic Initializer Example
Here's how to create a simple initializer:
struct Rectangle {
var width: Double
var height: Double
// Custom initializer
init(width: Double, height: Double) {
self.width = width
self.height = height
}
// Computed property
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 10.0, height: 5.0)
print("Rectangle area: \(rect.area)")
Output:
Rectangle area: 50.0
🔹 Failable Initializers
Some initializers can fail and return nil:
struct Temperature {
var celsius: Double
init?(fahrenheit: Double) {
if fahrenheit < -459.67 {
return nil // Absolute zero in Fahrenheit
}
celsius = (fahrenheit - 32) * 5/9
}
init?(celsius: Double) {
if celsius < -273.15 {
return nil // Absolute zero in Celsius
}
self.celsius = celsius
}
}
if let temp1 = Temperature(fahrenheit: 100) {
print("Temperature: \(temp1.celsius)°C")
}
if let temp2 = Temperature(celsius: -300) {
print("This won't print - invalid temperature")
} else {
print("Invalid temperature!")
}
Output:
Temperature: 37.77777777777778°C
Invalid temperature!