简体   繁体   English

声明符合Swift协议的变量或常量

[英]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? 在Swift中,如何声明符合协议的变量(或常量)?

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 . 但有时你使用遗留的objc id,你可能会得到一个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? 或者你可能想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. 但是, 您无法构造协议的实例,因为协议实际上并不提供它们指定的要求的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM