Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4.1 - Subclass UIImage

I get Overriding non-@objc declarations from extensions is not supported error when subclass UIImage with custom init after upgrading to Swift 4.1

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

Thanks for your help

like image 962
Daniel Nilsson Avatar asked Apr 11 '18 09:04

Daniel Nilsson


2 Answers

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

This init method is declared in the extension of the UIImage class.

The error pretty much says that if a function is declared in the extension than it can't be overridden in this way

class Foo: UIImage {

}

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

var temp = Foo(bar: "Hello")

You could try to achieve the desired result in this way.

like image 123
Ajay Singh Mehra Avatar answered Oct 09 '22 23:10

Ajay Singh Mehra


The problem seems to be caused by the init(bar:) designed initializer, if you convert it to a convenience one, then the class will compile:

class Foo: UIImage {

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

    // no longer need to override the required initializers
}

Seems that once you add a designated initializer (aka a non-convenience one), Swift will also enforce overrides for all required initializers from the base class. And for UIImage we have one that lives in an extension (not sure how it got there, likely was auto-generated, as myself wasn't able to add a required initializer in an extension). And you run into the compiler error in discussion.

like image 31
Cristik Avatar answered Oct 10 '22 01:10

Cristik