且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从NSObject继承时,不会调用泛型中使用的swift子类

更新时间:2022-11-23 13:41:21

我能够确认您的结果并将其作为错误提交, https://bugs.swift.org /browse/SR-10285 .

I was able to confirm your results and submitted it as a bug, https://bugs.swift.org/browse/SR-10617. Turns out this is a known issue! I was informed (by good old Hamish) that I was duplicating https://bugs.swift.org/browse/SR-10285.

在我提交的错误中,我为您的示例创建了一个简洁紧凑的示例,适合发送给Apple:

In my bug submission, I created a clean compact reduction of your example, suitable for sending to Apple:

protocol P {
    init()
    func doThing()
}

class Wrapper<T:P> {
    func go() {
        T().doThing()
    }
}

class A : NSObject, P {
    required override init() {}
    func doThing() {
        print("A")
    }
}

class B : A {
    required override init() {}
    override func doThing() {
        print("B")
    }
}

Wrapper<B>().go()

在Xcode 9.2上,我们得到"B".在Xcode 10.2上,我们得到"A".仅此一项就足以提出错误报告.

On Xcode 9.2, we get "B". On Xcode 10.2, we get "A". That alone is enough to warrant a bug report.

在我的报告中,我列出了三种解决此问题的方法,所有这些方法都确认这是一个错误(因为它们应该都不起作用)

In my report I listed three ways to work around the issue, all of which confirm that this is a bug (because none of them should make any difference):

  • 使通用参数化类型的约束为A而不是P

  • make the generic parameterized type's constraint be A instead of P

,或将协议P标记为@objc

或者,没有从NSObject继承的内容

or, don't have A inherit from NSObject

更新:结果(来自Apple自己的发行说明)还有另一种方式:

UPDATE: And it turns out (from Apple's own release notes) there's yet another way:

  • 将A的init标记为@nonobjc
  • mark A's init as @nonobjc