【问题标题】:Swift guard check for nil file - unexpectedly found nil对 nil 文件进行 Swift 保护检查 - 意外发现 nil
【发布时间】:2018-06-13 11:50:18
【问题描述】:

我正在尝试使用保护语句来检查此文件是否可用。

guard UIImage(contentsOfFile: Bundle.main.path(forResource: imageName, ofType: "png")!) != nil else {
    print("\(imageName).png file not available")
    return
}

但是我在警戒线上遇到了崩溃:

致命错误:在展开可选值时意外发现 nil

imageName 不是可选的。它是一个有值的字符串。

nil 正是我要测试的,那么为什么guard 语句会崩溃?

【问题讨论】:

标签: swift optional guard


【解决方案1】:

结合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)!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多