问题描述
weak
引用在Swift中似乎不起作用,除非协议
被声明为 @objc
,我不想在一个纯粹的Swift应用程序。
weak
references don't seem to work in Swift unless a protocol
is declared as @objc
, which I don't want in a pure Swift app.
这段代码给出一个编译错误( weak
不能应用于非类型 MyClassDelegate
):
This code gives a compile error (weak
cannot be applied to non-class type MyClassDelegate
):
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate {
}
我需要在协议前加上 @objc
,然后才可以使用。
I need to prefix the protocol with @objc
, then it works.
问题:什么是纯快捷方式来完成 weak
委托
?
Question: What is the 'pure' Swift way to accomplish a weak
delegate
?
推荐答案
您需要将协议的类型声明为 class
。
You need to declare the type of the protocol as class
.
protocol ProtocolNameDelegate: class {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
我的理解是使用 class
,你保证这个协议只能用于类,没有其他的东西像枚举或结构。
My understanding is that using class
, you guarantee that this protocol will be used only on classes and no other stuff like enums or structs.
这篇关于如何在“纯”Swift(w / o @objc)中做出弱协议参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!