[swift] 프로토콜 조합 (Protocol Composition)
프로토콜 조합은 쉼표(,)를 사용하여 두 개 이상의 프로토콜 타입을 결합합니다. 예를 들어 protocol1 & protocol2
형태로 사용됩니다.
protocol Printable {
func getDescription() -> String
}
protocol Drawable {
func draw()
}
struct Button: Printable, Drawable {
func getDescription() -> String {
return "This is a button"
}
func draw() {
// draw button
}
}
func drawAndPrint(object: Printable & Drawable) {
print(object.getDescription())
object.draw()
}
let button = Button()
drawAndPrint(object: button)
위 예제에서 Button
구조체는 Printable
과 Drawable
프로토콜을 모두 따르는 타입으로 선언됩니다. drawAndPrint
함수는 Printable & Drawable
을 준수하는 객체를 매개변수로 받아 출력과 그리기를 수행하는 간단한 함수입니다.
이렇게하면 각각의 프로토콜을 따로 구현한 것과 같은 효과를 얻을 수 있지만, 코드의 재사용성과 모듈화가 더 뛰어나고, 더욱 견고한 코드를 만들 수 있습니다.