Multiple Type Constraints in Swift

后端 未结 4 1484
暖寄归人
暖寄归人 2020-12-04 07:14

Let\'s say I have these protocols:

protocol SomeProtocol {

}

protocol SomeOtherProtocol {

}

Now, if I want a function that takes a gener

4条回答
  •  [愿得一人]
    2020-12-04 07:59

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

    protocol SomeProtocol {
        /* ... */
    }
    
    protocol SomeOtherProtocol {
        /* ... */        
    }
    

    1. Using & operator

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

    2. Using where clause

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

    3. Using where clause and & operator

    func someFunc(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(arg: T) {
        /* ... */   
    }
    

提交回复
热议问题