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

问题描述

引用在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.

此代码给出了编译错误(不能应用于非类类型 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.

问题:什么是纯快速完成 委托

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:40