"Type involving Objective-C type parameter cannot be used for associated type of protocol"?

In the pursuit of creating a very simple existential wrapper for NSLayoutAnchor, I've written the following code:

protocol LayoutAnchor {
    associatedtype Anchor: AnyObject
}

extension NSLayoutAnchor: LayoutAnchor {
    typealias Anchor = AnchorType
}

And received the following error:

Type 'NSLayoutAnchor<AnchorType>.Anchor' involving Objective-C type parameter 'AnchorType' cannot be used for associated type 'Anchor' of protocol 'LayoutAnchor'

This error is somewhat baffling to me, because the NSLayoutAnchor declaration leads me to believe this should be possible, given that its AnchorType is constrained to AnyObject there, as well:

open class NSLayoutAnchor<AnchorType> : NSObject, NSCopying, NSCoding where AnchorType : AnyObject

Does anyone know why this does not work as expected?

1 Like

Hello,

Did you ever figure out why this didn't work?

Lightweight generics in Objective-C use type erasure, and there’s no way to know what the concrete type argument passed to the class is from an instance (or metatype) of that class, hence you cannot refer to type parameters in the associated type.