How to use associatedType in protocol conforming to AnyObject

83 views Asked by At

After my code stopped compiling I was able to break it down to simple issue:

When using an associatedType that conforms to a protocol, which again conforms to AnyObject my code no longer compiles not even giving a proper error:

Command SwiftCompile failed with a nonzero exit code

How can I make sure a parent property conforms to any object implementing a specific protocol that conforms to AnyObject (i.e. is a class)?

Simple code example (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)
        }
    }
}
1

There are 1 answers

0
AnderCover On

Do you really need ParentProtocol.parentType to be an associated type ?

Your code compiles with :

protocol ChildProtocol: ParentProtocol {
    var parent: ParentProtocol! { get set }
}