【问题标题】:Closure use of non-escaping parameter - Swift 3 issue非转义参数的闭包使用 - Swift 3 问题
【发布时间】:2017-03-08 12:34:50
【问题描述】:

我知道 Swift 3 的变化,其中 @nonescaping 是闭包的默认行为。

我已经成功地更改了我的大部分代码,但我的代码中有一部分我无法摆脱 非转义参数的闭包使用可能允许它转义 编译错误。

我尝试将 @escaping 添加到 updateHandler 参数和 UpdatedInProgressHandler 类型别名,但似乎还不够。

谁能帮我找出问题的原因?

定义类型别名和函数的代码:

// Typealiases used to clean up closures
typealias UpdateInProgressCompletion = () -> ()
typealias UpdateInProgressCancelCompletion = () -> ()
typealias UpdateInProgressHandler = ((_ completed: @escaping UpdateInProgressCompletion) -> ()) -> ()

// Method for wrapping the presentation and dismissal of the custom alert controller
func presentUpdateInProgress(_ taskIdentifier: String?, alertMessage: String?, alertHeader: String? = nil, updateHandler: @escaping UpdateInProgressHandler, cancel cancelHandler: UpdateInProgressCancelCompletion? = nil) {

    let updateInProgressAlert = self.updateInProgressAlert( taskIdentifier, alertMessage: alertMessage, alertHeader: alertHeader ) { action in
        cancelHandler?()
        Logger.debug("User cancelled update")
    }

    updateInProgressAlert.present(completion: nil)

    updateHandler { (completion) in
        updateInProgressAlert.dismiss(completion: completion)
    }
}

调用 presentUpdateInProgress 函数时,我得到“关闭使用非转义参数“updateCompleted”可能允许逃逸”错误的代码。

    self.presentUpdateInProgress(taskIdentifier, alertMessage: "My alert message", updateHandler: { (updateCompleted) -> () in

        let task = CreateModelTask(completionHandler: { (resultObject) -> () in
            updateCompleted { // this generates the error

                //Do some stuff with received result
            }
        })

        task.taskIdentifier = taskIdentifier
        SyncManager.sharedManager.addTaskToQueue(task)
    })

【问题讨论】:

标签: swift swift3


【解决方案1】:

updateCompleted(_ completed: @escaping UpdateInProgressCompletion) -> () 类型,因为它是一个函数参数本身,意味着它默认是非转义的(请注意,“默认非转义”行为仅适用于函数闭包参数,请参阅this Q&A,以及有关主题的its dupe target

因此,为了让updateCompleted 逃脱,您需要在typealias 中将(_ completed: @escaping UpdateInProgressCompletion) -> () 标记为@escaping

typealias UpdateInProgressHandler = (<b>@escaping</b> (_ completed: @escaping UpdateInProgressCompletion) -&gt; ()) -&gt; ()

【讨论】:

  • 非常感谢@Hamish,我错过了必须转义 updateCompleted 函数参数的部分。
  • 谢谢@Hamish,转义关闭已清除我的请求。尽管如此,我对非转义有疑问。实例函数和非转义闭包有什么区别?
猜你喜欢
  • 2020-05-04
  • 1970-01-01
  • 2017-07-02
  • 2017-06-30
  • 2017-01-29
  • 1970-01-01
  • 2022-10-21
  • 2016-12-23
  • 1970-01-01
相关资源
最近更新 更多