【发布时间】:2017-05-17 12:03:11
【问题描述】:
我无法让以下代码工作:
@objc protocol Child { }
@objc protocol Parent {
var child: Child { get }
}
class ChildImpl: Child {
// not part of the `Child` protocol
// just something specific to this class
func doSomething() { }
}
class ParentImpl: Parent {
let child = ChildImpl()
func doSomething() {
// need to be able to access `doSomething`
// from the ChildImpl class
childImpl.doSomething()
}
// this would solve the problem, however can't access the ChildImpl members
// that are not part of the protocol
// let child: Child = ChildImpl()
// as well as this, however maintaining two properties is an ugly hack
// var child: Child { return childImpl }
// private let childImpl = ChildImpl()
}
我得到的错误:
类型“ParentImpl”不符合协议“Parent”。
是否要添加协议存根?
基本上我有两个父子协议和两个实现这两个协议的类。但是,编译器仍然无法识别 ChildImpl 是 Child。
如果我在 Parent 上使用关联类型,我可以消除错误
protocol Parent {
associatedtype ChildType: Child
var child: ChildType { get }
}
,但是我需要有可供 Objective-C 使用的协议,并且还需要能够引用 child 作为实际的具体类型。
是否有解决方案不涉及重写Objective-C 中的协议,或者不添加重复的属性声明只是为了避免问题?
【问题讨论】:
-
见this Q&A——在你的情况下一个可行(但不是特别好的)解决方案是定义一个
Child!到ParentImpl类型的虚拟属性来满足协议要求(然后有您的实际财产类型为ChildImpl!)。 -
@Hamish,我也评估了这种方法,但是(正如你所说)它不是很好,它需要维护两个具有相同角色的属性:(
-
@Cristik 是的:/不幸的是,我认为这可能是在 Swift 支持之前你能管理的最好的方法——尽管我希望有人能用更好的解决方法证明我错了。跨度>
-
我发现这是 Swift 编译器中的一个错误 tbh
标签: objective-c swift protocols