Initialization
In Swift, initializers are special methods that can be called to create a new instance of a particular type. They're akin to "constructors" in other programming languages. Initializers prepare the new instance of a class, structure, or enumeration for use, which involves setting an initial value for each stored property and performing any other necessary setup.
Default Initializers:
Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself.
class ShoppingItem {
var name: String = ""
var quantity: Int = 0
}
let item = ShoppingItem() // name is "" and quantity is 0
Memberwise Initializers for Structure Types:
Swift provides a memberwise initializer by default for structures. This initializer is not available for class types.
struct Point {
var x: Double
var y: Double
}
let point = Point(x: 0.0, y: 0.0)
Custom Initializers:
You can provide a custom initializer that requires specific information when you create an instance of a class or struct.
class Animal {
var name: String
// Custom initializer
init(name: String) {
self.name = name
}
}
let aDog = Animal(name: "Rex")
Failable Initializers:
Failable initializers are used for cases where invalid conditions may cause the initialization to fail. These initializers return an optional value.
struct Item {
var name: String
var price: Double
// Failable initializer
init?(name: String, price: Double) {
if name.isEmpty || price <= 0 {
return nil
}
self.name = name
self.price = price
}
}
if let validItem = Item(name: "Vase", price: 42) {
print(validItem.price) // Prints: 42.0
}
if let invalidItem = Item(name: "", price: 42) {
// This won't execute because the initializer will return nil
print(invalidItem.price)
}
Initializer Delegation for Value Types (Structures):
struct Size {
var width: Double, height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
// Initializer Delegation
init(side: Double) {
self.init(width: side, height: side)
}
}
let someSize = Size(side: 50) // width and height will be 50
Class Inheritance and Initialization:
In classes, designated initializers are primary initializers that initialize all properties introduced by the class and call a superclass initializer to continue initialization up the chain.
class Vehicle {
var numberOfWheels: Int
init(wheels: Int) {
self.numberOfWheels = wheels
}
}
class Bicycle: Vehicle {
var hasBasket: Bool
init(hasBasket: Bool) {
self.hasBasket = hasBasket
super.init(wheels: 2) // Calling a designated initializer from the superclass
}
}
let bike = Bicycle(hasBasket: true)
These examples showcase various ways initializers can be used in Swift, depending on the requirements of your classes and structures.