ios - 尝试用 Swift 协议(protocol)理解一些东西

标签 ios swift swift4 swift-protocols

我最近继承了一个用 Swift 编写的完全没有文档记录的、意大利面条式的和极其错误的项目。

我在这里和那里整理一些东西,并且在每个协议(protocol)声明中都遇到了这个:

protocol SomeProtocol: class { ...

字面上的 : class - 这不是其他内容的占位符。

我的问题是:: class 实现或声明了什么?

个人从来没有把 : class 放在后面,我通常保留它用于从其他协议(protocol)继承。我删除了几个没有结果,但我想在继续之前我应该​​检查实际目的(如果有的话)。

最好的问候,

弗兰基

最佳答案

: class 表示这个协议(protocol)只能被一个类遵守。

其中一个用例是委托(delegate)。 delegate 属性通常声明为 weak 以避免循环保留。例如:

class MyCoolClass {
    weak var delegate: MyCoolClassDelegate?
}

如果 MyCoolClassDelegate 声明如下:

protocol MyCoolClassDelegate { }

然后结构也可以符合它。但是结构类型不能声明为 weak!因此,出现这个错误:

'weak' may only be applied to class and class-bound protocol types, not 'MyCoolClassDelegate'

这就是为什么您需要将其声明为: class

关于ios - 尝试用 Swift 协议(protocol)理解一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47606291/

相关文章:

ios - Swift 4 - iOS 11 搜索栏范围不会出现,因为它应该

ios - swift 4.0 : Overriding 'prepare' must be as available as declaration it overrides

iOS HealthKit 在 session 期间跟踪用户步数

iOS 当按下按钮 "next"加载新行表单时解析 Swift

ios - 为不适用于 ipad 的 View 添加边框

ios - UIBezierPath addLine : wrong length uppon draw

构建服务无法启动构建操作 : internal error: failed to send the system info to the build service

c# - 在 Xamarin iOS 中检索 JSON 数据

ios - CollectionView 滚动更改选定的单元格

android - 是否能够创建一个 iPhone 应用程序,不通过 wifi 或 3G 使用互联网,而是使用手机上的 WIFI 发送信息