【问题标题】:Extension can't access generic parameters at runtime扩展无法在运行时访问泛型参数
【发布时间】:2017-06-01 16:54:56
【问题描述】:

我正在使用 AWS Cognito,在文档中说我必须添加此功能。

但我收到此错误:

泛型 Objective-C 类的扩展无法在运行时访问该类的泛型参数

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
        })

    }
}

【问题讨论】:

    标签: objective-c swift amazon-web-services swift3 amazon-cognito


    【解决方案1】:

    对于那些在 Swift 5 中遇到此问题的人,请尝试在方法中添加 @objc 修饰符。请在下面找到示例:

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

    【讨论】:

    • 它看起来与错误消息中的内容相符。为我工作。
    【解决方案2】:

    如果没有上下文,我不能说您是否真的按照错误消息提示的方式进行操作,但是有一个开放的错误报告描述了这个问题(实际上没有使用有问题的代码):

    ObjC

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

    斯威夫特

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

    这两种扩展方法都导致“泛型Objective-C类的扩展无法访问该类的泛型参数 运行时”。但是,两者都没有真正做这样的事情(至少 不明确)。

    如果您阅读错误报告中的 cmets,您会看到名为“Vasili Silin”的用户描述了在尝试扩展 AWSTask 时遇到此问题,因此您可能必须考虑其他方法,直到此错误得到解决.

    【讨论】:

    • 在我为 Core Data NSFetchRequest 函数设置的扩展中遇到此错误。根据链接报告中的一个想法,我将扩展名更改为类。不得不四处更改 func 调用,但它确实有效。
    【解决方案3】:

    我刚刚遇到同样的错误并以这种方式解决它:

    扩展 yourClass 其中 T == yourType {}

    【讨论】:

    • 这是我的问题。在约束结构类型时,Swift 不喜欢继承约束 (T: YourType) 更是一个问题。在这种情况下,使用显式等式约束 (T == YourType) 可以修复很多这些神秘的编译器错误。
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2013-09-30
    相关资源
    最近更新 更多