Search code examples
iosswiftxcodeswift3today-extension

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

Solution

  • 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.