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.
source to share
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 }
.
source to share