11.3 Default Initializers
Swift provides a default initializer to any class that:
- provides default values to all its properties
- does not provide at least 1 initializer itself
An example for a simple ShoppingList class is shown below:
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
Stucture types automatically receive a member-wise initalizer if they do not define their own initializer. It allows initial values of the structure's properties to be passed by name, and works even if the properties are not given default values. An example for a Size structure with an automatically generated init(width:,height:)
intializer is shown below.
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)