如何在“纯"Swift(没有@objc)中进行弱协议引用 [英] How can I make a weak protocol reference in 'pure' Swift (without @objc)

查看:30
本文介绍了如何在“纯"Swift(没有@objc)中进行弱协议引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

weak 引用似乎在 Swift 中不起作用,除非将 protocol 声明为 @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 delegate 的纯"Swift 方法是什么?

Question: What is the 'pure' Swift way to accomplish a weak delegate?

推荐答案

需要将协议类型声明为AnyObject.

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

使用 AnyObject 你说只有类可以符合这个协议,而结构或枚举不能.

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

这篇关于如何在“纯"Swift(没有@objc)中进行弱协议引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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