在 Swift 中,协议从 class 关键字继承是什么意思? [英] In Swift, what does it mean for protocol to inherit from class keyword?

查看:35
本文介绍了在 Swift 中,协议从 class 关键字继承是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,协议继承自 class 关键字是什么意思?

例如

protocol MyDelegate: class {}

解决方案

为什么不呢?因为 weak 关键字只对 ARC 适用的引用类型有意义.ARC 不适用于值类型.如果没有用 class 指定我们的协议,我们不能保证我们的 delegate 属性设置为引用类型.(如果我们不使用 weak,我们很可能会创建一个保留循环.)

In Swift, what does it mean for protocol to inherit from class keyword?

e.g.

protocol MyDelegate: class {

}

解决方案

The gist of Starscream's answer is correct, but it misses the why which I think is important here. It comes down to ARC and memory management.

Swift is a language of reference types and value types. Classes are reference types, while everything else is a value type. Effectively, we're not really specifying that the protocol inherits from class... it's more like we're specifying that the protocol can only be implemented by reference types.

And why is that important?

It's important, because without it, we can't use the weak keyword with the protocol.

protocol ExampleProtocol {}

class DelegatedClass {
    weak var delegate: ExampleProtocol?
}

This generates the error:

'weak' cannot be applied to non-class type 'ExampleProtocol'

And why not? Because the weak keyword only makes sense with reference types to which ARC applies. ARC does not apply to value types. And without specifying our protocol with class, we cannot guarantee that our delegate property is set to a reference-type. (And if we don't use weak, we're most likely creating a retain cycle.)

这篇关于在 Swift 中,协议从 class 关键字继承是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆