为什么关键词“弱"可以仅适用于类和类绑定协议类型 [英] Why can the keyword "weak" only be applied to class and class-bound protocol types

查看:26
本文介绍了为什么关键词“弱"可以仅适用于类和类绑定协议类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Swift 中将变量声明为 weak 时,有时我会收到来自 Xcode 的错误消息:

When I'm declaring variables as weak in Swift, I sometimes get the error message from Xcode:

'weak' 只能应用于类和类绑定的协议类型

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

我只是想知道为什么关键字 weak 只能应用于类和类绑定的协议类型?背后的原因是什么?

I was just wondering why keyword weak can only applied to class and class-bound protocol types? What is the reason behind it?

推荐答案

weak 是引用类型(相对于值类型,例如 structs 和内置值类型).

weak is a qualifier for reference types (as opposed to value types, such as structs and built-in value types).

引用类型允许您对同一对象有多个引用.当最后一个强引用停止引用该对象时,该对象将被释放(弱引用不计算在内).

Reference types let you have multiple references to the same object. The object gets deallocated when the last strong reference stops referencing it (weak references do not count).

另一方面,值类型是通过副本分配的.引用计数不适用,所以 weak 修饰符对它们没有意义.

Value types, on the other hand, are assigned by copy. Reference counting does not apply, so weak modifier does not make sense with them.

这篇关于为什么关键词“弱"可以仅适用于类和类绑定协议类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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