gpt4 book ai didi

swift - Swift 协议(protocol)中的弱属性只能是类或类绑定(bind)协议(protocol)类型

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:34 30 4
gpt4 key购买 nike

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

'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 }

}

最佳答案

协议(protocol)目前不能要求将属性实现为存储属性。

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

class C {}

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

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

这是 filed as a bug , 和 SE-0186将对协议(protocol)中的属性要求使用 weakunowned 在 Swift 4.1 中(在 Swift 3 和 4 模式下)是一个警告,在 Swift 5 中是一个错误。

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

关于swift - Swift 协议(protocol)中的弱属性只能是类或类绑定(bind)协议(protocol)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699813/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com