非逃逸参数的闭包使用 - Swift 3问题

4
我知道Swift 3中的改变,其中@nonescaping是闭包的默认行为。我已经成功地更改了很多关于这些改变的代码,但有一部分代码我无法摆脱闭包使用非逃逸参数可能导致其逃逸编译错误。 我尝试在updateHandler参数和UpdatedInProgressHandler typealias上添加@escaping,但似乎不够。请问是否有人能帮助我找出问题所在? 以下是定义类型别名和函数的代码:
// 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函数时,我遇到了“Closure use of non-escaping parameter "updateCompleted" may allow if to escape”的错误。

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

1个回答

3
updateCompleted的类型是(_ completed: @escaping UpdateInProgressCompletion) -> (),作为一个函数参数本身,默认情况下它是不可逃逸的(请注意,“默认情况下不可逃逸”行为仅适用于函数闭包参数,参见此问答以及有关该主题的其重复目标)。 因此,为了允许updateCompleted逃逸,您需要在typealias中将(_ completed: @escaping UpdateInProgressCompletion) -> ()标记为@escaping
typealias UpdateInProgressHandler = (@escaping (_ completed: @escaping UpdateInProgressCompletion) -> ()) -> ()

非常感谢@Hamish,我错过了必须转义updateCompleted函数参数的部分。 - peroseth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接