【问题标题】:Swift 4.1 - Subclass UIImageSwift 4.1 - 子类 UIImage
【发布时间】:2018-04-11 09:53:13
【问题描述】:

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

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

感谢您的帮助

【问题讨论】:

    标签: swift uiimage swift4.1


    【解决方案1】:
    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")
    

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

    【讨论】:

      【解决方案2】:

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

      class Foo: UIImage {
      
          convenience init(bar: String) { super.init() }
      
          // no longer need to override the required initializers
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多