init(parameters) {
// 초기화 코드
}
클래스의 초기화 메서드(Initializer)에 관한 특징을 설명하겠습니다.
let car = Car.init(speed: 20)
Car 인스턴스 생성시 초기화 메소드를 호출하지만 보통은 생략을 한다.
오버라이딩된 초기화 메서드가 호출되면, 부모 클래스에서 정의한 초기화 메서드가 자동으로 실행되지 않습니다. 이로 인해 부모 클래스에서 초기화된 프로퍼티 초기화가 누락될 수 있습니다. 이런 상황을 방지하기 위해서는 오버라이딩된 초기화 메서드 내에서 부모 클래스의 초기화 메서드를 명시적으로 호출해야 합니다. 이를 위해 super.init을 사용합니다.
class BaseClass {
var baseValue: Double
init() {
self.baseValue = 0.0 // 부모 클래스에서 프로퍼티 초기화
print("Base Init")
}
}
class Subclass: BaseClass {
var additionalValue: Double
override init() {
self.additionalValue = 0.0
super.init() // 부모 클래스의 초기화 메서드를 호출하여 부모 클래스에서 프로퍼티 초기화를 실행
self.baseValue = 10.0 // 자식 클래스에서 추가적인 초기화 작업 수행
print("Subclass Init")
}
}
만약 부모 클래스에서 초기화 메서드를 정의하지 않거나 기본 초기화 메서드만 정의한 경우, 자식 클래스에서 초기화 메서드를 호출할 때 자동으로 부모 클래스의 초기화 메서드가 호출됩니다.
class Parent {
var parentProperty: Int
init() {
parentProperty = 0
print("Parent Init")
}
}
class Child: Parent {
var childProperty: Int
init(childValue: Int) {
childProperty = childValue
// 부모 클래스의 초기화 메서드는 자동으로 호출됨
print("Child Init")
}
}