Programing

스위프트의 다중 유형 제약

lottogame 2020. 7. 19. 09:51
반응형

스위프트의 다중 유형 제약


이 프로토콜이 있다고 가정 해 봅시다.

protocol SomeProtocol {

}

protocol SomeOtherProtocol {

}

이제 제네릭 형식을 취하는 함수를 원하지만 해당 형식을 준수해야하는 SomeProtocol경우 다음을 수행 할 수 있습니다.

func someFunc<T: SomeProtocol>(arg: T) {
    // do stuff
}

그러나 여러 프로토콜에 대한 유형 제약 조건을 추가하는 방법이 있습니까?

func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) {

}

비슷한 것들이 쉼표를 사용하지만이 경우 다른 유형의 선언을 시작합니다. 여기 내가 시도한 것이 있습니다.

<T: SomeProtocol | SomeOtherProtocol>
<T: SomeProtocol , SomeOtherProtocol>
<T: SomeProtocol : SomeOtherProtocol>

당신은 사용할 수 있습니다 where 절 은 (모두 충족되어야합니다 그중를) 원하는 쉼표로 구분대로 많은 요구 사항으로 지정할 수 있습니다

스위프트 2 :

func someFunc<T where T:SomeProtocol, T:SomeOtherProtocol>(arg: T) {
    // stuff
}

스위프트 3 & 4 :

func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
    // stuff
}

또는 더 강력한 where 절 :

func someFunc<T>(arg: T) where T:SomeProtocol, T:SomeOtherProtocol{
    // stuff
}

물론 프로토콜 구성 (예 :)을 사용할 수 protocol<SomeProtocol, SomeOtherProtocol>있지만 유연성이 떨어집니다.

Using를 where사용하면 여러 유형이 관련된 경우를 처리 할 수 ​​있습니다.

여러 위치에서 재사용하기 위해 프로토콜을 작성하거나 작성된 프로토콜에 의미있는 이름을 부여 할 수 있습니다.


두 가지 가능성이 있습니다.

  1. Jiaaro의 답변에 표시된 where 절사용하십시오 .

    func someFunc<T where T : SomeProtocol, T : SomeOtherProtocol>(arg: T) {
        // do stuff
    }
    
  2. 당신은 사용하는 프로토콜 구성 유형 :

    func someFunc<T : protocol<SomeProtocol, SomeOtherProtocol>>(arg: T) {
        // do stuff
    }
    

Swift 3.0으로의 진화는 약간의 변화를 가져옵니다. 우리의 두 가지 선택은 이제 조금 다르게 보입니다.

whereSwift 3.0에서 절 사용 :

where절은 이제 가독성을 개선하기 위해 함수 서명의 끝으로 이동하고있다. 다중 프로토콜 상속은 이제 다음과 같습니다 :

func someFunc<T>(arg: T) where T:SomeProtocol, T:SomeOtherProtocol {

}

protocol<>Swift 3.0 에서 구문 사용 :

구성을 사용하는 protocol<>구성은 더 이상 사용되지 않습니다. 이전 protocol<SomeProtocol, SomeOtherProtocol>은 다음과 같습니다.

func someFunc<T:SomeProtocol & SomeOtherProtocol>(arg: T) {

}

참고 문헌.

More info on the changes for where are here: https://github.com/apple/swift-evolution/blob/master/proposals/0081-move-where-expression.md

And, more on the changes for the protocol<> construct are here: https://github.com/apple/swift-evolution/blob/master/proposals/0095-any-as-existential.md


Swift 3 offers up to 3 different ways to declare your function.

protocol SomeProtocol {
    /* ... */
}

protocol SomeOtherProtocol {
    /* ... */        
}

1. Using & operator

func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
    /* ... */
}

2. Using where clause

func someFunc<T>(arg: T) where T: SomeProtocol, T: SomeOtherProtocol {
    /* ... */
}

3. Using where clause and & operator

func someFunc<T>(arg: T) where T: SomeProtocol & SomeOtherProtocol {
    /* ... */        
}

Also note that you can use typealias in order to shorten your function declaration.

typealias RequiredProtocols = SomeProtocol & SomeOtherProtocol

func someFunc<T: RequiredProtocols>(arg: T) {
    /* ... */   
}

참고URL : https://stackoverflow.com/questions/24089145/multiple-type-constraints-in-swift

반응형