In Swift, how would I declare a variable that explicitly states that it conforms to some protocol? The objective-c equivalent would be @property id<NSObject>
From my understanding, doing this:
var a: NSObject
declares a variable that is of type NSObject protocol but I don't to do that, I want to declare a variable of type AnyObject
that conforms. I'm also interested in finding out how to declare an array of objects in which each object conforms to that protocol.
There is really no need for AnyObject
here; if all you care about is conformance to a protocol Proto
, you can simply write var a: Proto
. (In some cases your protocol may use Self
or other things that require it to be used as a generic constraint; you would then use class C<T: Proto> { var a: T }
.
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