A compilation error with associated type

This is a simplified fragment that doesn't compile for me. How do I fix it?
The version of this code without associated type compiles ok.

// typealias T = Int // this works

protocol Foo: AnyObject {
    associatedtype T // this does not work
    func foo(_: T) -> T
    var value: T { get set }
}

struct Holder {
    weak var object: (any Foo)?
}

func bar(holders: [Holder]) {
    holders.forEach { holder in
        let object = holder.object!
        let value = object.foo(object.value) // 🛑 Member 'foo' cannot be used on value of type 'any Foo'; consider using a generic constraint instead
        object.value = value
    }
}

to call object.foo(...) you need an instance of type T, but you erased the type by using any

You know that the type of object.value should work, but the compiler doesn't. Solution? Work in a context where compiler knows the types:

private extension Foo {
    func callMyFooPassingMyValueAndAssignToMyValue() {
        self.value = self.foo(self.value)
    }
}

func bar(holders: [Holder]) {
    holders.forEach { holder in
        let object = holder.object!
        object.callMyFooPassingMyValueAndAssignToMyValue()
    }
}
3 Likes