[swift] Objective-C에서 Swift 상속 및 다중 상속의 처리 방식

Objective-C와 Swift의 상속 및 다중 상속 처리 방식에 대해 설명하고자 합니다.

Objective-C에서의 상속

Objective-C는 클래스 기반의 객체 지향 언어이며, 상속을 지원합니다. Objective-C에서는 @interface 키워드를 사용하여 부모 클래스의 메서드 및 속성을 하위 클래스로 상속할 수 있습니다. 또한 Objective-C는 단일 상속만을 지원합니다.

@interface ParentClass : NSObject
@property NSString *name;
- (void)printName;
@end

@interface ChildClass : ParentClass
@end

Objective-C에서의 다중 상속

Objective-C는 다중 상속을 공식적으로 지원하지 않습니다. 대신, 프로토콜(Protocol)을 사용하여 다중 상속과 유사한 기능을 구현할 수 있습니다.

@protocol Protocol1
- (void)method1;
@end

@protocol Protocol2
- (void)method2;
@end

@interface MyClass : NSObject <Protocol1, Protocol2>
@end

Swift에서의 상속

Swift는 Objective-C와는 다르게 클래스, 구조체, 열거형 모두에서 상속을 지원합니다. 클래스의 상속은 class 키워드를 사용하여 선언하며, 단일 상속만을 지원합니다.

class ParentClass {
    var name: String = ""
    func printName() {
        print(self.name)
    }
}

class ChildClass: ParentClass {
}

Swift에서의 다중 상속

Swift는 클래스에서의 다중 상속을 지원하지 않습니다. 대신에 프로토콜을 통해 다중 상속과 유사한 기능을 지원합니다.

protocol Protocol1 {
    func method1()
}

protocol Protocol2 {
    func method2()
}

class MyClass: Protocol1, Protocol2 {
    func method1() {
        // Implement method1
    }
    func method2() {
        // Implement method2
    }
}

Objective-C와 Swift에서의 상속 및 다중 상속의 처리 방식에 대해 알아보았습니다. Objective-C는 클래스를 사용하여 상속을 처리하고, 프로토콜을 활용하여 다중 상속과 유사한 기능을 구현합니다. Swift는 클래스, 구조체, 열거형에서 상속을 지원하지만, 클래스에서는 다중 상속을 지원하지 않습니다. 대신 프로토콜을 통해 다중 상속과 유사한 기능을 구현할 수 있습니다.

더 자세한 내용은 Apple Developer Documentation를 참고하시기 바랍니다.