7

Overriding non-@objc declarations from extensions is not supported升级到 Swift 4.1 后使用自定义初始化子类 UIImage 时出现错误

class Foo: UIImage {

    init(bar: String) { }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Overriding non-@objc declarations from extensions is not supported
    required convenience init(imageLiteralResourceName name: String) {
        fatalError("init(imageLiteralResourceName:) has not been implemented")
    }
}

谢谢你的帮助

4

2 回答 2

6
extension UIImage {

    /// Creates an instance initialized with the given resource name.
    ///
    /// Do not call this initializer directly. Instead, initialize a variable or
    /// constant using an image literal.
    required public convenience init(imageLiteralResourceName name: String)
}

这个 init 方法是在UIImage类的扩展中声明的。

该错误几乎表明,如果在扩展中声明了一个函数,那么它就不能以这种方式被覆盖

class Foo: UIImage {

}

extension Foo {
    convenience init(bar :String) {
        self.init()
    }
}

var temp = Foo(bar: "Hello")

您可以尝试以这种方式达到预期的结果。

于 2018-04-11T12:28:33.920 回答
2

该问题似乎是由init(bar:)设计的初始化程序引起的,如果将其转换为方便的初始化程序,则该类将编译:

class Foo: UIImage {

    convenience init(bar: String) { super.init() }

    // no longer need to override the required initializers
}

似乎一旦你添加了一个指定的初始化器(也就是一个不方便的初始化器),Swift 还将强制覆盖基类中所有必需的初始化器。因为UIImage我们有一个存在于扩展中(不确定它是如何到达那里的,可能是自动生成的,因为我自己无法在扩展中添加所需的初始化程序)。而且您在讨论中遇到编译器错误。

于 2019-09-03T06:40:43.293 回答