programing

Swift의 다중 형식 제약 조건

golfzon 2023. 5. 9. 23:24
반응형

Swift의 다중 형식 제약 조건

제가 다음 프로토콜을 가지고 있다고 가정해 보겠습니다.

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>), 하지만 유연성이 조금 떨어집니다.

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

여러 장소에서 재사용할 프로토콜을 구성하거나, 구성된 프로토콜에 의미 있는 이름을 지정하기 위해 프로토콜을 구성할 수 있습니다.

스위프트 5:

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

프로토콜이 인수 옆에 있기 때문에 이것은 더 자연스럽게 느껴집니다.

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

  1. 지아로의 답변에 나와 있는 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) {

}

참고 자료.

에 대한 변경 사항에 대한 추가 정보where여기: https://github.com/apple/swift-evolution/blob/master/proposals/0081-move-where-expression.md

프로토콜 <> 구성의 변경 사항에 대한 자세한 내용은 다음과 같습니다. https://github.com/apple/swift-evolution/blob/master/proposals/0095-any-as-existential.md

Swift 3은 기능을 선언하는 최대 3가지 방법을 제공합니다.

protocol SomeProtocol {
    /* ... */
}

protocol SomeOtherProtocol {
    /* ... */        
}

사용&교환입니다.

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

사용where

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

사용where절과&교환입니다.

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

또한 사용할 수 있습니다.typealias함수 선언을 단축하기 위해.

typealias RequiredProtocols = SomeProtocol & SomeOtherProtocol

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

언급URL : https://stackoverflow.com/questions/24089145/multiple-type-constraints-in-swift

반응형