Types conforming to multiple protocols in swift

Swift

Swift Problem Overview


I have an Objective-C variable that conforms to multiple protocols.

id <NSObject, NSCopying, NSCoding> identityToken; 

How would I represent this type in Swift?

Swift Solutions


Solution 1 - Swift

This should work:

var identityToken: NSObjectProtocol & NSCopying & NSCoding 

Note you have to use NSObjectProtocol instead of NSObject in swift.

Here are some additional examples:

Array of objects conforming to multiple protocols:

var array: [NSObjectProtocol & NSCopying & NSCoding]

Function with a parameter that conforms to multiple protocols:

func foo(param: NSObjectProtocol & NSCopying & NSCoding) {
    
}

For Swift version before 3.1, use:

var identityToken: (NSObjectProtocol, NSCopying, NSCoding)

Solution 2 - Swift

Swift 3

var idToken: NSObjectProtocol & NSCopying & NSCoding

func foo(_ delegateAndDataSource: UICollectionViewDelegate & UICollectionViewDataSource) { ... }

Solution 3 - Swift

Seems like you could also type-alias the composite protocols, which may come in handy if you plan on using the same combination of protocol multiple times.

typealias IDToken = NSObjectProtocol & NSCopying & NSCoding

Same examples as given in the accepted answer, using a type-alias:

var idToken: IDToken

var array: [IDToken] = []

func foo(param: IDToken) { ... }

Solution 4 - Swift

The above answer from conner is correct, however you often should implement a separate protocol that itself inherits from the other protocols, and allows you more flexibility, should you want to add additional protocol methods later or change the top level protocols.

internal protocol MyOtherProtocol : NSObjectProtocol, NSCopying, NSCoding {
    func someOtherNecessaryMethod()
}

Then utilized:

var identityToken : MyOtherProtocol

Solution 5 - Swift

For generics this works as well:

func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew McCormackView Question on Stackoverflow
Solution 1 - SwiftConnorView Answer on Stackoverflow
Solution 2 - SwiftKalzemView Answer on Stackoverflow
Solution 3 - SwiftPhlippie BosmanView Answer on Stackoverflow
Solution 4 - SwiftJoel TeplyView Answer on Stackoverflow
Solution 5 - SwiftScottyBladesView Answer on Stackoverflow