我不能让下面的代码工作:亲子关系协议和ObjC可用性
@objc protocol Child { }
@objc protocol Parent {
var child: Child { get }
}
class ChildImpl: Child {
func doSomething() { }
}
class ParentImpl: Parent {
let child = ChildImpl()
// 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()
}
我得到的错误:
Playground execution failed: error: Tests.playground:3:7: error: type 'ParentImpl' does not conform to protocol 'Parent' class ParentImpl: Parent { ^
Tests.playground:4:9: note: candidate has non-matching type 'ChildImpl' var child = ChildImpl()
基本上我有两个亲子协议,和两个实现这两个协议的类。但编辑仍然抱怨ChildImpl
不是Child
,这是不正确的。
我可以让错误消失,如果我对Parent
protocol Parent {
associatedtype ChildType: Child
var child: ChildType { get }
}
使用关联的类型,但我需要有可用的Objective-C的协议,同时还需要能够引用child
为实际的具体类型。
是否有解决方案,不涉及重写Objective-C
中的协议,或者不添加重复的属性声明只是为了避免该问题?
相关:[斯威夫特协议继承和协议conformence问题( HTTP://计算器。com/questions/40410884/swift-protocol-inheritance-and-protocol-conformence-issue)(另请参阅:[协议不符合自身吗?](http://stackoverflow.com/questions/33112559/protocol-doesnt -conform到本身))。 – dfri
请参见[本问答](http://stackoverflow.com/q/42561685/2976878) - 在您的案例中,一种可行(但不是特别好)的解决方案是将“Child!”类型的虚拟属性定义为“ParentImpl '以满足协议要求(然后让您的实际属性为'ChildImpl!'类型)。 – Hamish
@Hamish,然后我评估了这种方法,但是(正如你所说)它不是很好,它需要保持两个属性具有相同的作用:( – Cristik