Types conforming to multiple protocols in 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) { ... }

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)

Swift 3

var idToken: NSObjectProtocol & NSCopying & NSCoding

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

Tags:

Swift