如何在“纯”Swift(w / o @objc)中做出弱协议参考 [英] How can I make a weak protocol reference in 'pure' Swift (w/o @objc)

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

问题描述

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)中做出弱协议参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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