Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare class variable as conforming to Swift protocol

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.

like image 979
barndog Avatar asked Jan 11 '23 00:01

barndog


1 Answers

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 }.

like image 140
jtbandes Avatar answered Jan 16 '23 21:01

jtbandes