Extension can't access generic parameters at runtime

For those who have this issue in Swift 5, try adding @objc modifier to the method. Please find the example below:

extension NSLayoutAnchor {

    @objc func constrainEqual(_ anchor: NSLayoutAnchor<AnchorType>, constant: CGFloat = 0) {
        let constraint = self.constraint(equalTo: anchor, constant: constant)
        constraint.isActive = true
    }
}

Without context I can't say if you are actually doing what the error message prompts you with, but there is an open bug report describing this issue (where no offending code is actually used):

  • SR-2708: Extending ObjC generics in Swift 3 does not compile

ObjC:

@interface MySet<T : id<NSCopying>> : NSObject
@end

Swift:

class Foo { }
struct Bar { }

extension MySet {
    func foo() -> Foo { return Foo() }
    func bar() -> Bar { return Bar() }
}

Both of the extension methods result in "Extension of a generic Objective-C class cannot access the class's generic parameters at runtime". However, neither really does anything like that (at least not explicitly).

If you read the comments to the bug report, you'll see that a user named 'Vasili Silin' describes having this issue when attempting to extend AWSTask, so you might have to consider alternative approaches until this bug is resolved.


I just got the same error and solve it this way :

extension yourClass where T == yourType {}