如何在符合AnyObject的协议中使用associatedType

问题描述 投票:0回答:1

在我的代码停止编译后,我能够将其分解为简单的问题:

当使用符合协议的

associatedType
时,它再次符合
AnyObject
我的代码不再编译
甚至没有给出正确的错误:

命令 SwiftCompile 失败,退出代码非零

如何确保

parent
属性符合实现符合
AnyObject
的特定协议(即是一个类)的任何对象?

简单代码示例(MRE):

protocol ParentProtocol: AnyObject { // without AnyObject this runs fine
    var value: Int { get set }
}
protocol ChildProtocol: ParentProtocol {
    associatedtype parentType: ParentProtocol
    var parent: parentType! { get set }
}

class Test {
    var child: (any ChildProtocol)?
    
    func call() {
        if let child = child {
            print(child.parent.value)
        }
    }
}
swift swift-protocols
1个回答
0
投票

您真的需要

ParentProtocol.parentType
成为关联类型吗?

您的代码编译为:

protocol ChildProtocol: ParentProtocol {
    var parent: ParentProtocol! { get set }
}
© www.soinside.com 2019 - 2024. All rights reserved.