[swift] 상속과 초기화 메서드

상속은 객체지향 프로그래밍에서 중요한 개념 중 하나입니다. 스위프트에서는 클래스 간의 상속을 지원하며, 상속 관련된 초기화 메서드에 대해 알아보겠습니다.

상속 기본

클래스 A가 클래스 B를 상속받을 때, B는 A의 모든 속성과 메서드를 상속받습니다. 이때, B는 A의 자식 클래스(child class)이 되고, A는 B의 부모 클래스(parent class)가 됩니다.

class A {
    var propertyA: Int

    init(propertyA: Int) {
        self.propertyA = propertyA
    }

    func methodA() {
        // do something
    }
}

class B: A {
    var propertyB: String

    init(propertyA: Int, propertyB: String) {
        self.propertyB = propertyB
        super.init(propertyA: propertyA)
    }

    func methodB() {
        // do something
    }
}

위의 예시에서 B 클래스는 A 클래스를 상속받고, A의 속성과 메서드를 사용할 수 있습니다.

초기화 메서드의 재정의

부모 클래스에서 정의된 초기화 메서드를 자식 클래스에서 필요에 맞게 재정의할 수 있습니다. 이때, override 키워드를 사용하여 부모 클래스의 초기화 메서드를 재정의합니다.

class A {
    var propertyA: Int

    init(propertyA: Int) {
        self.propertyA = propertyA
    }
}

class B: A {
    var propertyB: String

    override init(propertyA: Int) {
        self.propertyB = "default"
        super.init(propertyA: propertyA)
    }
}

위의 예시에서 B 클래스는 A 클래스의 초기화 메서드를 재정의하여 propertyB를 초기화하고 있습니다.

designated 및 convenience 초기화 메서드

스위프트에서는 designated 초기화 메서드와 convenience 초기화 메서드를 구분합니다. designated 초기화 메서드는 클래스의 기본 초기화 메서드이며, convenience 초기화 메서드는 보조적인 역할을 수행하는 초기화 메서드입니다.

class A {
    var propertyA: Int

    init(propertyA: Int) {
        self.propertyA = propertyA
    }

    convenience init() {
        self.init(propertyA: 0)
    }
}

위의 예시에서 convenience init() 메서드는 designated 초기화 메서드를 호출하여 propertyA를 기본값으로 초기화하는 convenience 초기화 메서드를 구현한 것입니다.

상속과 초기화 메서드를 올바르게 이해하는 것은 객체지향 프로그래밍을 제대로 활용하는 데 중요합니다. 상속을 활용하여 코드의 재사용성을 높이고, 초기화 메서드를 적절히 활용하여 객체 생성을 관리하는 것이 중요합니다.