Swift 기초 문법 - 22. 프로토콜 상속

정성윤·2023년 7월 19일
0

Swift 이론

목록 보기
24/64

스위프트에서는 프로토콜 상속(Protocol Inheritance)을 통해 하나 이상의 프로토콜을 상속받을 수 있습니다.

프로토콜 상속을 사용하면 다른 프로토콜의 요구사항을 상속하고, 추가적인 요구사항을 정의할 수 있습니다.

protocol ProtocolA {
    // ProtocolA에 정의된 요구사항
}
protocol ProtocolB: ProtocolA {
    // ProtocolA를 상속한 ProtocolB에 정의된 요구사항
}
protocol ProtocolC: ProtocolA, ProtocolB {
    // ProtocolA와 ProtocolB를 상속한 ProtocolC에 정의된 요구사항
}

위의 예시에서 ProtocolB는 ProtocolA를 상속받았으며, "C는 A,B를 상속받았습니다.

프로토콜 상속을 사용하여 기존 프로토콜의 요구사항을 확장하거나 추가적인 요구사항을 정의할 수 있습니다.

protocol Printable {
    func print()
}
protocol PrintableWithPrefix: Printable {
    var prefix: String { get }
}
struct MyStruct: PrintableWithPrefix {
    var prefix: String = "Prefix:"

    func print() {
        Swift.print("\(prefix) Printing...")
    }}

참고(출처) : 개발하는 정대리, 야곰(Swift5)

profile
이유있는 스위프트 개발자

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

이 글을 읽고 많이 배웠습니다.

답글 달기