Check in UIImage.init existence of image in bundle

42 views Asked by At

I want to write init for UIImage, which check if image exists in Assets of .main bundle (application level) - takes it from .main, and if not - takes it from .currentModule (package level)

For now it works like only taking from .currentModule:

public extension UIImage {
    convenience init?(originalName: String) {
        self.init(named: originalName, in: .currentModule, with: nil)
    }
}

and I want to find way if self.init(named: originalName, in: .main, with: nil) returns nil, call self.init(named: originalName, in: .currentModule, with: nil) so write something like

public extension UIImage {
    convenience init?(originalName: String) {
        if let _ = self.init(named: originalName, in: .main, with: nil) 
    else
        self.init(named: originalName, in: .currentModule, with: nil)
    }
}

But it does not compile

This example compiles, but here is double work initialising image in .main bundle:

public extension UIImage {
    convenience init?(originalName: String) {
        if originalName == "" {
            return nil
        } else if let _ = UIImage(named: originalName, in: .main, with: nil) {
            self.init(named: originalName, in: .main, with: nil)
        } else {
            self.init(named: originalName, in: .currentModule, with: nil)
        }
    }
}

(Just if you wonder for what to use init for this purpose and with 'originalName: String' parameter, - we and our clients already have large codebase which uses such init and there is an enum instead of String)

1

There are 1 answers

3
Emrecan Öztürk On

Try this:

public extension UIImage {
    convenience init?(originalName: String) {
        if let image = UIImage(named: originalName, in: .main, with: nil) {
            self.init(cgImage: image.cgImage!)
        } else if let image = UIImage(named: originalName, in: .currentModule, with: nil) {
            self.init(cgImage: image.cgImage!)
        } else {
            return nil
        }
    }
}