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 4 allows multiple protocols to be called at once with the help of protocol composition.
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.
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() }
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With