Declare class variable according to Swift protocol

In Swift, how would one declare a variable that explicitly states that it conforms to some protocol? The equivalent of objective-c would be @property id<NSObject>

From my understanding, doing this:

var a: NSObject

declares a variable that is of the NSObject protocol type, but I don't, I want to declare a variable of the type AnyObject

that matches. I am also curious about how to declare an array of objects, each of which conforms to this protocol.

+3


source to share


3 answers


There is no need here AnyObject

; if everything you care about follows the protocol Proto

, you can just write var a: Proto

. (In some cases, your protocol may use Self

or other things that require it to be used as a general constraint, then you would use class C<T: Proto> { var a: T }

.



+4


source


The protocol is NSObject

imported into Swift as NSObjectProtocol

(due to a name conflict with the class NSObject

), so it will be



var a: NSObjectProtocol

      

+2


source


It might be easier in Swift 4. You can simultaneously declare a variable of some class corresponding to the protocol. You can do it like this:

var someVar: ClassA & ProtocolA & ProtocolB

      

+1


source







All Articles