I can't get the following code to work:
@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()
}
The error I get:
Type 'ParentImpl' does not conform to protocol 'Parent'.
Do you want to add protocol stubs?
Basically I have two parent-child protocols, and two classes that implement the two protocols. But still, the compiler doesn't recognize that that ChildImpl
is a Child
.
I can make the errors go away if I use an associated type on Parent
protocol Parent {
associatedtype ChildType: Child
var child: ChildType { get }
}
, however I need to have the protocols available to Objective-C, and also need to be able to reference child
as the actual concrete type.
Is there a solution to this that doesn't involve rewriting the protocols in Objective-C
, or doesn't add duplicate property declarations just to avoid the problem?