我想检查图像是否存在,但是在失败的初始化中...我可以做得很丑,但实际上我想知道self == nil
是否可能...
extension UIImage {
convenience init?(_ name:String) {
let image = UIImage(named:name)
guard image != nil else { Assert("image \(name) missing yo"); return nil }
self.init(named: name)
}
}
更干净但无法编译
extension UIImage {
convenience init?(_ name:String) {
self.init(named: name)
if self == nil { Assert("image \(name) missing yo") }
}
}
静态函数不像init那样有趣
extension UIImage {
static func with(_ name:String) -> UIImage? {
let image = UIImage(named:name)
if image == nil { Assert("image \(name) missing yo") }
return image
}
}
提前感谢您的时间
**编辑**
也许我两个都需要?
extension UIImage {
convenience init?(_ name:String) {
self.init(named:name)
}
}
extension Optional where Wrapped == UIImage {
init?(_ name:String) {
self.init(name)
if self == nil {
Assert("image \(name) missing yo")
}
}
}
答案 0 :(得分:4)
我不确定我能否正确回答您的问题。但我认为您想要这样的东西:(让我知道它是否有帮助或为什么不帮忙)
extension Optional where Wrapped == UIImage {
init?(_ name:String) {
self.init(name)
if self == nil {
Assert("image \(name) missing yo")
}
}
}