Initialization is the process of preparing an instance of a class, structure, or enumeration for use.
Unlike Objective-C, Swift initializers do not return a value.
Their primary role is to ensure that every property on a new instance is correctly set to an initial value before the object is used for the first time.
init MethodYou define an initializer by writing the init keyword. It behaves exactly like an instance method, but without the func keyword.
class Fahrenheit {
var temperature: Double
// This runs immediately when the object is created
init() {
temperature = 32.0
}
}
let currentTemp = Fahrenheit()
print("The default temperature is \(currentTemp.temperature)")
Initializers can take parameters, just like normal functions.
This allows you to pass in custom data the exact moment an object is created.
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
// 'self' distinguishes the property from the parameter
self.name = name
self.age = age
}
}
// Passing data directly upon creation
let user = Person(name: "Akash", age: 25)
print(user.name)
If you declare a struct, Swift is incredibly helpful: it automatically generates a "memberwise initializer" for you behind the scenes!
This means you don't even have to write an init method for structs if you don't want to.
struct Size {
var width: Double
var height: Double
}
// Swift automatically generated this initializer for us!
let mySize = Size(width: 10.0, height: 20.0)
print(mySize.width)
Note: Classes do NOT receive an automatic memberwise initializer.
Sometimes initialization can fail (e.g., if invalid data is passed in). You can define a failable initializer by writing init?. It returns an Optional that will be nil if initialization fails.
Which type in Swift automatically receives a free "memberwise initializer" generated by the compiler?