[swift] 상위 클래스를 참조하는 Swift 초기화 메서드

Swift에서 클래스의 초기화 메서드를 구현할 때, 상위 클래스를 참조해야 할 때가 있습니다. 이때 super 키워드를 사용하여 상위 클래스의 초기화 메서드를 호출할 수 있습니다.

다음은 super 키워드를 사용하여 상위 클래스를 참조하는 초기화 메서드의 예시입니다.

class Vehicle {
    var numberOfWheels: Int

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

class Car: Vehicle {
    var numberOfSeats: Int

    init(numberOfWheels: Int, numberOfSeats: Int) {
        self.numberOfSeats = numberOfSeats
        super.init(numberOfWheels: numberOfWheels)
    }
}

위의 예시에서 Car 클래스는 Vehicle 클래스를 상속받고 있습니다. Car 클래스의 초기화 메서드에서 super.init(numberOfWheels: numberOfWheels)를 호출하여 Vehicle 클래스의 초기화 메서드를 호출하고 있습니다. 이렇게 함으로써 Car 클래스의 인스턴스를 초기화할 때, numberOfWheels 속성을 설정할 수 있습니다.

이와 같은 방식으로 상위 클래스를 참조하는 초기화 메서드를 구현할 수 있습니다.

참조: