简体   繁体   English

逃生关闭swift3

[英]Escaping closure swift3

I am having an issue regarding closure escaping.The closure is defined as escaping but somehow the compiler always gives an error. 我有一个关于闭包转义的问题。闭包被定义为转义,但以某种方式编译器总是会给出错误。

The error i get is 我得到的错误是

Closure use of non-escaping parameter 'completion' may allow it to escape . 闭包使用非转义参数'completion'可以使其逃脱

I have also mentioned the places where i get the error. 我也提到了我得到错误的地方。

Following is the code where closure is defined. 以下是定义闭包的代码。

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)

Now it is used here. 现在在这里使用。

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)
    }
  }
})

I have seen a lot of other questions regarding this error issue but none seems to solve my problem.Any help will be highly appreciated.Thanks 我已经看到了许多有关此错误问题的其他问题,但似乎都无法解决我的问题。任何帮助将不胜感激。

Making the closure optional solved the issue.It was an eventual hit and trial. 使关闭成为可选选项解决了这个问题,这是最终的尝试。

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

I saw this closure was passed to a function which accepts an optional closure.Then I decided to make it optional.When i made it optional the error was gone. 我看到这个闭包被传递给一个接受可选闭包的函数,然后我决定将其设置为可选,当我将其设置为可选时,错误消失了。 And xcode was giving me a wrong error perhaps. xcode可能给了我一个错误的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM