Initialization
Johnson
Introduction
What is initialization?
Initialization is preparing instance class, struct or
enumeration for use
Setting initial value
struct Hello {
let sayHello: String
init(){
sayHello = “hello!!”
}
}
Setting initial value
struct Hello {
var sayHello = “hello!!”
}
let hello = Hello()
Custom parameter
struct Hello {
var sayHello: String
init(whatToSay word: String) {
sayHello = word
}
init(anotherHello word: String) {
sayHello = word
}
}
let saySomething = Hello(whatToSay: “HELLO”)
let sayAnother = Hello(anotherHello: “GREETING”)
Custom parameter
struct Hello {
var helloOne, helloTwo: String
init(helloOne: String, helloTwo: String) {
self.helloOne = helloOne
self.helloTwo = helloTwo
}
}
let hello = Hello(helloOne: “HELLO”, helloTwo:
“GREETING”)
Custom parameter
struct Hello {
var helloOne, helloTwo: String
init(_ word1: String, _ word2: String) {
helloOne = word1
helloTwo = word2
}
}
let hello = Hello(“HELLO”, “GREETING”)
Initializing delegate
1. A designated initializer must call a designated
initializer from its immediate superclass.
2. A convenience initializer must call another initializer
from the same class.
3. A convenience initializer must ultimately call a
designated initializer.
Failable initialization
init?(hello: String){
if hello.isEmpty{return nil}
self.hello = hello
}

Initialization