在闭包中解开之前检查过的选项会导致崩溃

问题描述 投票:0回答:1

我遇到了一次非常罕见的崩溃,可能涉及完美的时机(关闭应用程序或进入后台状态?)此代码的最后一行

  fileprivate static func showNextDialog()
  {
    let next=futureDialogs.first
    if next != nil
    {
      futureDialogs.remove(next!)
      delay(0.01){showDialog(next!)}
    }
  }

导致以下崩溃

#0  (null) in Swift runtime failure: Unexpectedly found nil while unwrapping an Optional value ()
#1  0x00000001049ff7ac in closure #1 in static InterfaceManager.showNextDialog() at ...
#2  (null) in partial apply for closure #1 in static InterfaceManager.showNextDialog() ()

功能延迟如下:

func delay(_ delay:Double,_ closure:@escaping ()->())
{
  DispatchQueue.main.asyncAfter(
    deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

唯一的可选变量

next
被let捕获并检查
nil
。有人知道会发生什么吗?

swift crash closures
1个回答
0
投票

next
是什么类型?看起来它是一个引用类型,这意味着您不能捕获它的值,而只能捕获该值的地址。

showNextDialog
等待
delay
时,
next
的值可能会更改为
nil
。作为可能的解决方案,您可以在
nil
的完成处理程序中再次检查它是否为
delay

delay(0.01) {
  if let next {
    showDialog(next)
  }
}

附注一个相关的小建议:避免强制展开并采用

guard let
/
if let
语法,而不是检查与
nil
是否相等。

© www.soinside.com 2019 - 2024. All rights reserved.