Swift 保护检查 nil 文件 - 意外发现 nil
Swift guard check for nil file - unexpectedly found nil
我正在尝试使用保护语句来检查此文件是否可用。
guard UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!) != nil else {
print("\(imageName).png file not available")
return
}
但我在警戒线上遇到了崩溃:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
imageName
不是可选的。它是一个有值的字符串。
nil
正是我要测试的内容,那么为什么 guard
语句崩溃了?
结合使用 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
}
综上所述,如果图像实际上应该在您的应用程序包中并且这只是一个临时问题,例如忘记正确定位文件,那么请不要使用 guard 并继续强制-展开。您希望应用程序在早期开发过程中崩溃,以便您可以解决问题。
let image = UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!)!
最后一件事。您可以使用以下方法更轻松地获取图像:
let image = UIImage(named: imageName)!
我正在尝试使用保护语句来检查此文件是否可用。
guard UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!) != nil else {
print("\(imageName).png file not available")
return
}
但我在警戒线上遇到了崩溃:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
imageName
不是可选的。它是一个有值的字符串。
nil
正是我要测试的内容,那么为什么 guard
语句崩溃了?
结合使用 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
}
综上所述,如果图像实际上应该在您的应用程序包中并且这只是一个临时问题,例如忘记正确定位文件,那么请不要使用 guard 并继续强制-展开。您希望应用程序在早期开发过程中崩溃,以便您可以解决问题。
let image = UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!)!
最后一件事。您可以使用以下方法更轻松地获取图像:
let image = UIImage(named: imageName)!