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'
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.
From the docs:
Protocols are named types, and thus they can appear in all the same places in your code as other named types, as discussed in Protocols as Types. However, you can't construct an instance of a protocol, because protocols do not actually provide the implementations for the requirements they specify.
链接地址: http://www.djcxy.com/p/20744.html下一篇: 声明一个符合Swift协议的变量或常量