【问题标题】:Escaping closure swift3逃避关闭swift3
【发布时间】:2018-06-14 01:15:32
【问题描述】:

我遇到了关于闭包转义的问题。闭包被定义为转义,但不知何故编译器总是给出错误。

我得到的错误是

闭包使用非转义参数'completion'可能会允许它转义

我还提到了我得到错误的地方。

以下是定义闭包的代码。

final internal class AnimationTemplate {

var  template: ((CompletionFunc) -> AnimationFunc)

init(template:  @escaping (CompletionFunc) -> AnimationFunc)
{
    self.template = template
}

func perform(with completion: CompletionFunc) { template(completion)() }
}

internal typealias CompletionFunc =  (( Bool) -> Void)

internal typealias AnimationFunc = (() -> Void)

现在在这里使用。

AnimationQueue.shared.enqueue(animation: AnimationTemplate { completion in

  //Error here
  //Closure use of non-escaping parameter 'completion' may allow it to escape
  return {

     (0 ..< self.placeholderViews.count).forEach {

      let current: PasscodeSignPlaceholderView = self.placeholderViews[$0]

      let state: PasscodeSignPlaceholderView.State = $0 < inputLength ? .active : .inactive

      //Error here
      //Closure use of non-escaping parameter 'completion' may allow it to escape
      current.setState(to: state, with: completion)
    }
  }
})

我已经看到了很多关于这个错误问题的其他问题,但似乎没有一个可以解决我的问题。任何帮助将不胜感激。谢谢

【问题讨论】:

  • 指定您的错误。
  • @dahiya_boy 指定了错误。请参阅更新后的问题。
  • 试试这些12
  • @dahiya_boy 我已经看到了所有这些答案,但它并没有解决问题。我已经指定了可能的转义,但它总是给我这个错误。
  • 把这个@escaping (CompletionFunc) -&gt; AnimationFunc改成@escaping (CompletionFunc) -&gt; Void试试。

标签: ios swift3 xcode8


【解决方案1】:

使关闭成为可选解决了这个问题。这是一个最终的成功和试验。

 internal typealias CompletionFunc =  (( Bool) -> Void)?

我看到这个闭包被传递给一个接受可选闭包的函数。然后我决定将其设为可选。当我将其设为可选时,错误就消失了。 并且 xcode 可能给了我一个错误的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2011-03-10
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多