Jun Yeong Lee Jun Yeong Lee - 1 year ago 118
Swift Question

Instance method 'widgetPerformUpdate(completionHandler:)' nearly matches optional requirement 'widgetPerformUpdate(completionHandler:)'

I'm new in today extension, I've got this warning, does anyone know how to match the optional requirement?


Instance method 'widgetPerformUpdate(completionHandler:)' nearly matches optional requirement 'widgetPerformUpdate(completionHandler:)' of protocol 'NCWidgetProviding'


func widgetPerformUpdate(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData

let result = performFetch()
if result == .newData{
tableView.reloadData()
self.preferredContentSize = tableView.contentSize
}
completionHandler(result)
}

Answer Source

Write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

func widgetPerformUpdate(completionHandler: (@escaping(NCUpdateResult) -> Void)) {
    // Perform any setup necessary in order to update the view.
    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData

    let result = performFetch()
    if result == .newData{
        tableView.reloadData()
        self.preferredContentSize = tableView.contentSize
    }
    completionHandler(result)
}

This function basically takes a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn’t called until the operation is completed—the closure needs to escape, to be called later.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download