结合guard 和强制展开是矛盾的。 guard 的常见用途之一是 guard let,它可以安全地防范 nil 并消除强制解包的需要。
我会将您的代码重做如下:
guard let imagePath = Bundle.main.path(forResource: imageName, ofType: "png"), let image = UIImage(contentsOfFile: imagePath) else {
print("\(imageName).png file not available")
return
}
// Use image here as needed
如果您实际上并不需要该图像,但您只是想确保可以创建图像,您可以将其更改为:
guard let imagePath = Bundle.main.path(forResource: imageName, ofType: "png"), UIImage(contentsOfFile: imagePath) != nil else {
print("\(imageName).png file not available")
return
}
说了这么多,如果图像实际上应该在您的应用程序包中,并且它只是一个临时问题,例如忘记正确定位文件,那么不要使用保护并继续强制解包.您希望应用在早期开发过程中崩溃,以便解决问题。
let image = UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!)!
最后一件事。您可以使用以下方法更轻松地获取图像:
let image = UIImage(named: imageName)!