Swift 协议中的弱属性可能只是一个类或类绑定的协议类型 [英] Weak property in a Swift protocol may only be a class or class-bound protocol type

查看:204
本文介绍了Swift 协议中的弱属性可能只是一个类或类绑定的协议类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个在 Viper 架构中使用的协议,以使用具有弱属性的协议在 Viper 组件之间建立连接,但我收到以下错误消息:

I would like to define a protocol which is used in a Viper architecture to establish a connection between a Viper components using a protocol with a weak property but I get the following error message:

'weak' 只能应用于类和类绑定的协议类型,不是'Self.ViperViewClass'

'weak' may only be applied to class and class-bound protocol types, not 'Self.ViperViewClass'

protocol ViperPresenter: class {

    associatedtype ViperViewClass
    weak var view: ViperViewClass! { get set }

}

推荐答案

协议目前不能要求将属性实现为 weak 存储属性.

Protocols can't currently require properties to be implemented as weak stored properties.

虽然 weakunowned 关键字目前在属性要求中是允许的,但它们没有任何作用.以下是完全合法的:

Although the weak and unowned keywords are currently allowed on property requirements, they have no effect. The following is perfectly legal:

class C {}

protocol P {
  weak var c: C? { get set }
}

struct S : P {
  var c: C? // strong reference to a C instance, not weak.
}

这是作为错误提交,并且SE-0186 将使用weakunowned 在协议中的属性要求 Swift 4.1 中的警告(在 Swift 3 和 4 模式下),以及 Swift 5 中的错误.

This was filed as a bug, and SE-0186 will make the use of weak and unowned on property requirements in a protocol a warning in Swift 4.1 (in both Swift 3 and 4 modes), and an error in Swift 5.

但即使协议可以要求将属性实现为weakunowned存储属性,编译器也需要知道ViperViewClass 是一个类类型(也就是说,
associatedtype ViperViewClass : AnyObject).

But even if protocols could require properties to be implemented as weak or unowned stored properties, the compiler would need to know that ViperViewClass is a class type (i.e by saying
associatedtype ViperViewClass : AnyObject).

这篇关于Swift 协议中的弱属性可能只是一个类或类绑定的协议类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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