[swift] 10. 초기화
초기화 함수
- init() 사용
- init() 오버로딩 가능.
- 구조체의 초기화 시 프로퍼티 명으로 인자로 줄 수 있다.
구조체 생성
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
초기화 실패할 경우 ? 지정 가능
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
if let giraffe = someCreature {
print("An animal was initialized with a species of \(giraffe.species)")
}
// Prints "An animal was initialized with a species of Giraffe"
열거형 실패 가능 initializer
- 열거형 초기화 실패 init? 사용 시 ```swift enum TemperatureUnit { case kelvin, celsius, fahrenheit init?(symbol: Character) { switch symbol { case “K”: self = .kelvin case “C”: self = .celsius case “F”: self = .fahrenheit default: return nil } } }
let fahrenheitUnit = TemperatureUnit(symbol: “F”) if fahrenheitUnit != nil { print(“This is a defined temperature unit, so initialization succeeded.”) } // Prints “This is a defined temperature unit, so initialization succeeded.”
- 열거형 초기화 실패 Raw 값 대입
```swift
enum TemperatureUnit: Character {
case kelvin = "K", celsius = "C", fahrenheit = "F"
}
let fahrenheitUnit = TemperatureUnit(rawValue: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."
반드시 구현해야 하는 항목에 required keyword 삽입.
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}
클로저를 이용한 프로퍼티 초기화
Setting a Default Property value with a Closure or Function
class SomeClass {
let someProperty: SomeType = {
// create a default value for someProperty inside this closure
// someValue must be of the same type as SomeType
return someValue
}()
}
클로저 사용 시 클로저 실행 시점에 다른 프로퍼티가 초기화되었는 지 알 수 없기 때문에 self를 사용할 수 없음.
Deinit
// 소멸 시 호출
deinit {
// perform the deinitialization
}