Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension can't access generic parameters at runtime

I´m using AWS Cognito, in the doc it says I have to add this function.

But I´m getting this error:

Extension of a generic Objective-C class cannot access the class's generic parameters at runtime

extension AWSTask {
    public func continueWithExceptionCheckingBlock(completionBlock:@escaping (_ result: Any?, _ error: Error?) -> Void) {
        self.continue({(task: AWSTask) -> Any? in
            if let exception = task.exception {
                print("Fatal exception: \(exception)")
                kill(getpid(), SIGKILL);
            }
            let result: AnyObject? = task.result
            let error: NSError? = task.error as NSError?
            completionBlock(result, error)
            return nil
        })

    }
}
like image 375
Marius Schönefeld Avatar asked Jan 17 '17 14:01

Marius Schönefeld


2 Answers

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
    }
}
like image 106
Vadim Bulavin Avatar answered Nov 16 '22 15:11

Vadim Bulavin


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.

like image 8
dfrib Avatar answered Nov 16 '22 14:11

dfrib