Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types conforming to multiple protocols in swift

Tags:

swift

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

id <NSObject, NSCopying, NSCoding> identityToken;  

How would I represent this type in Swift?

like image 445
Drew McCormack Avatar asked Jun 04 '14 01:06

Drew McCormack


People also ask

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

Can a protocol implement another protocol Swift?

You can extend an existing type to adopt and conform to a new protocol, even if you don't have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand.

What is protocol type in Swift?

In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }

Can a protocol inherit from another protocol Swift?

One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top. Now we can make new types conform to that single protocol rather than each of the three individual ones.


1 Answers

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) 
like image 80
Connor Avatar answered Oct 04 '22 19:10

Connor