[swift] 자식 클래스가 부모 클래스의 속성과 메서드를 상속받는 방법

부모 클래스의 속성과 메서드를 자식 클래스에서 활용하기 위해서는 class 키워드를 사용하여 자식 클래스를 정의하고, 부모 클래스의 이름을 상속받을 클래스 이름 뒤에 콜론(:)을 붙인 후 사용하면 됩니다.

아래는 ParentClass를 부모 클래스로 하는 ChildClass의 예시 코드입니다.

class ParentClass {
    var parentProperty: String
    
    init(parentProperty: String) {
        self.parentProperty = parentProperty
    }
    
    func parentMethod() {
        print("This is a method in the parent class")
    }
}

class ChildClass: ParentClass {
    var childProperty: String
    
    init(parentProperty: String, childProperty: String) {
        self.childProperty = childProperty
        super.init(parentProperty: parentProperty)
    }
    
    func childMethod() {
        print("This is a method in the child class")
    }
}

위의 예시에서 ChildClassParentClass를 상속받았기 때문에 parentPropertyparentMethod를 사용할 수 있습니다.

이를테면childMethod에서 parentProperty를 활용할 수 있으며, 부모 클래스에서 정의한 메서드를 호출할 수 있게 됩니다.

상속에 관한 보다 자세한 내용은 Swift 공식문서를 참고하시기 바랍니다.

Swift 공식문서 - 상속