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'
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} ).
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.
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.
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!
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.
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