#StackBounty: #objective-c #swift #protocols Parent-child protocol relationship and ObjC availability

Bounty: 100

I can’t get the following code to work:

@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()

The errors I get:

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()

Basically I have two parent-child protocols, and two classes that implement the two protocols. But still, the compiler complains that ChildImpl is not a Child, which is not true.

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?

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.