【问题标题】:Swift3 : unexpectedly found nil while unwrapping an Optional valueSwift3:在展开可选值时意外发现 nil
【发布时间】:2017-04-09 04:26:12
【问题描述】:

我刚刚从 Swift 2 升级到 Swift 3,我面临着新的挑战...

我有一个播放器之前运行完美,但现在我遇到了以下问题:“在展开可选值时意外发现 nil”

这是我的代码:

print(audioselectionne)

let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: audioselectionne as String, ofType: "mp3")!)

我有:Optional("tiesto") 和崩溃...

我真的不明白问题出在哪里......

感谢您的帮助。

【问题讨论】:

  • 问题是你强制解开 pathForResource 的返回但它是 nil;找不到资源。
  • 是的,但我什么也没做,它正在使用 Swift 2
  • 你为什么会有沮丧的as String?删除它。

标签: ios swift swift3


【解决方案1】:

你应该解开可选的,也许使用可选绑定。

顺便说一句,您根本不应该使用路径字符串。直接使用网址即可,例如

guard let resource = audioselectionne, let alertSound = Bundle.main.url(forResource: resource, withExtension: "mp3") else {
    // handle file not found here
    return
}

// use alertSound here

【讨论】:

  • audioselectionne 来自 prepareforsegue 并像这样声明 var audioselectionne:String?
  • 我猜这里也是同样的问题...stackoverflow.com/questions/39537177/…
  • “找不到文件”?这与“意外发现零”非常不同。我正在回答展开可选问题(并建议您按照 Apple 的指导从路径转换为 ​​url)。如果找不到该文件,则该文件不在您的捆绑包中。此文件是在捆绑包还是文档文件夹中?
  • 实际上,当我这样做时:让 alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "tiesto" as String, ofType: "mp3")!)。它运行良好。但是当我试图输入我的变量时; audioselectionne, ,它不起作用。认为这是 uwrapping 可选的问题 ...
  • 这就是我做guard let resource = audioselectionne, let alertSound = ... 的原因,这样,我首先解开audioselectionne 可选,然后在Bundle.main.url(...) 调用中使用它...
【解决方案2】:

我认为Bundle.main.path 方法返回一个可选的String。当那是nil(因为找不到资源)时,强制展开它会导致您的错误。如果你想正确处理它,你必须检查nil

guard let path = Bundle.main.path(…) else {
    // resource not found, handle error
}

// now `path` is guaranteed to be non-nil
let alertSound = URL(fileURLWithPath: path)

【讨论】:

  • 问题是为什么 Swift3 找不到文件?这很奇怪
  • 也许路径与您之前在 Swift 3 中的代码不同,但您得到的错误 由 force-unwrap (!) 引起的。除非您必须这样做,否则不要强制展开值。
  • 实际上,如果这应该在 Bundle.main.path 中,那么您不应该处理错误,而是修复路径或确保资源在那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2016-10-18
  • 2018-09-22
  • 2016-06-26
  • 2016-03-12
  • 2021-12-30
相关资源
最近更新 更多