티스토리 뷰

반응형

Swift Docs > Protocol > Protocol Composition 을 읽다가 새로 알게된 내용!

 

protocol composition 은 one class type 을 포함할 수 있다고 합니다 😲

이는 required superclass를 명시할 때, 사용할 수 있습니다.

In addition to its list of protocols, a protocol composition can also contain one class type, 
which you can use to specify a required superclass.

 

protocol Named {
    var name: String { get }
}

class Location {
    var latitude: Double
    var longitude: Double
    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }
}

class City: Location, Named {
    var name: String
    init(name: String, latitude: Double, longitude: Double) {
        self.name = name
        super.init(latitude: latitude, longitude: longitude)
    }
}

func beginConcert(in location: Location & Named) {
    print("Hello, \(location.name)!")
    print("\(location.latitude), \(location.longitude)")
}

let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)
beginConcert(in: seattle)

// Prints
// "Hello, Seattle!"
// 47.6, -122.3

 

The beginConcert(in:) function takes a parameter of type Location & Named, which means “any type that’s a subclass of Location and that conforms to the Named protocol.” In this case, City satisfies both requirements.

 

 

+

추가적으로 테스트해보면

오직 하나의 class type만 protocol composition에 포함할 수 있도록 컴파일러가 강제하고 있는 것을 확인해볼 수 있습니다.

예를들어 SomeClass & SomeProtocol & OtherClass 을 하면 

아래와 같은 컴파일에러가 뜨고 

> Protocol-constrained type cannot contain class 'OtherClass' because it already contains class 'SomeClass'

 

SomeStruct & SomeProtocol 을 하면

아래와 같은 컴파일에러가 뜹니다. 

> Non-protocol, non-class type 'SomeStruct' cannot be used within a protocol-constrained type

 

 

반응형
댓글