Swift 4.1 - Subclass UIImage
Asked Answered
K

2

7

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

Knife answered 11/4, 2018 at 9:53 Comment(1)
UIImage is not for subclassing. Try composition instead of inheritanceEberhard
R
5
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.

Regalia answered 11/4, 2018 at 12:28 Comment(1)
It does not workEberhard
C
2

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.

Crossjack answered 3/9, 2019 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.