Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a variable or constant that conforms to a protocol in Swift

In Swift how do you declare a variable (or constant) that conforms to a protocol?

I've tried

let whatever: protocol <myProtocol>

and

let whatever: myProtocol

But when setting it I get the error

Cannot convert the expression's type '()' to type 'myProtocol'
like image 219
JuJoDi Avatar asked Jun 06 '14 00:06

JuJoDi


People also ask

Can we declare variable in protocol Swift?

Swift Protocol Requirements First things first, variables inside a protocol must be declared as a variable and not a constant( let isn't allowed). Properties inside a protocol must contain the keyword var . We need to explicitly specify the type of property( {get} or {get set} ).

Can we write constants in protocol in Swift?

Is there a method in Swift? In general it's not a good architecture to declare constants in interfaces. I know that many Java developers do that and then they are implementing that interface with constants to their classes but that's really abusing the concept of interfaces.

How do you declare a variable in Swift?

The var keyword is the only way to declare a variable in Swift. The most common and concise use of the var keyword is to declare a variable and assign a value to it. Remember that we don't end this line of code with a semicolon.

How do you use a variable in protocol?

Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get } . var height: Int {return 5} // error!


1 Answers

There is no such necessary to do such thing, because when you declare the type of your variable (or constant), it should be known if it is conforming a protocol or not. But in case sometimes you are using legacy objc id, you may get an AnyObject. In that situation, you can just do a downcast to convert it as a protocol type and use it.

let whatever: AnyObject = someObj
let conformProtocol = whatever as myProtocol

conformProtocol.callMethod()

Or you may want to use as? for a safer converting.

like image 183
onevcat Avatar answered Oct 13 '22 14:10

onevcat