[swift] Swift 초기화 메서드에서의 부모 클래스 호출

Swift에서는 객체를 초기화 할 때, 부모 클래스의 초기화 메서드를 호출해야하는 경우가 있습니다. 이를 위해 super.init()을 사용하여 부모 클래스의 초기화 메서드를 호출할 수 있습니다.

부모 클래스의 초기화 메서드는 자식 클래스의 초기화 메서드 내에서 호출되어야 합니다. 부모 클래스의 초기화 메서드를 호출하기 전에 자식 클래스에서 속성을 초기화해야 하므로, 이를 유의해야 합니다.

class ParentClass {
    var parentProperty: String
    
    init() {
        parentProperty = "Parent property"
    }
}

class ChildClass: ParentClass {
    var childProperty: String
    
    override init() {
        childProperty = "Child property"
        
        super.init()
    }
}

let childObject = ChildClass()
print(childObject.parentProperty) // 출력: "Parent property"
print(childObject.childProperty)  // 출력: "Child property"

위의 예시에서는 ParentClassChildClass라는 두 개의 클래스를 정의합니다. ParentClass에는 parentProperty라는 문자열 타입의 속성이 있고, ChildClasschildProperty라는 문자열 타입의 속성을 추가로 갖습니다.

ChildClass의 초기화 메서드인 init() 내에서 childProperty를 초기화하고, super.init()을 사용하여 ParentClass의 초기화 메서드를 호출합니다. 이렇게 함으로써 childObject를 인스턴스화 할 때 ParentClass의 초기화 메서드가 먼저 호출되고, 그 후에 ChildClass의 초기화 메서드가 호출됩니다.

따라서 childObjectparentProperty는 “Parent property”로 초기화되고, childProperty는 “Child property”로 초기화됩니다.

참고 자료