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)
Try this: