When creating Instance you can set Properties using Initializers (must set all Properties that have no initial values)
● Default Initializer (it is used only if there are no Dedicated Initializers)
● Designated Initializers init(parameters) { ... } (Can call other Designated Initializers)
Only mutating Methods can change Property values (new instance is created with new values).
Struct can only adopt Protocols (can't extend Struct/Class).
Default Initializer & Mutating Methods
//DECLARE STRUCTURE.
struct Person {
//PROPERTIES.
var name : String //Value must be set through Default Initializer
var age : Int = 0 //Has initial value.
//METHODS.
mutating func greet () -> (String) { //Mutating Method changes age
self.age = 20 //Otherwise 'self' is immutable
return("\(name) is \(age) years old")
}
}
//CREATE INSTANCE.
var john = Person(name: "John") //Call Default Initializer (Create Instance)
print(john.greet()) //John is 20 years old
john.name = "Bill" //You can change Property Value
print(john.name) //Bill
print(john.age ) //20
Designated Initializers
//DECLARE STRUCT.
struct Person {
//DECLARE FIELDS.
var name : String //Value must be set through Designated Initializer
var age : Int //Value must be set through Designated Initializer
//DESIGNATED INITIALIZER (with 2 parameters)
init(name: String, age: Int) {
self.name = name
self.age = age
}
//DESIGNATED INITIALIZER (with 1 parameter)
init(name: String) {
self.init(name: name, age: 50) //Call Designated Initializer with default age
}
}
//CREATE INSTANCE.
var person1 = Person(name: "John", age: 20) //Call Designated Initializer.
var person2 = Person(name: "Bill") //Call Designated Initializer.
dump(person2)