简体   繁体   中英

Swift: closure as parameter reports error

just writing a simple swift app and this error came up.

protocol FormDelegate {
    func formDidFinish(form: Form)
}

class Form {
    var delegate: FormDelegate?

    func testClosure(sender: () -> Void) {
    }
}

let form = Form()
form.testClosure {
//      let removeCommentToGetRidOfError = true
    form.delegate?.formDidFinish(form) // error: Cannot convert the expression's type '() -> () -> $T2' to type '()'
}

but when i insert the let statement, everything works. Any clue what's going on?

Problem is that closures have auto return, when there are no explicit return. In this case the return value is Void? as there is optional chaining involved. You can fix this by returning as last statement:

form.testClosure {
    form.delegate?.formDidFinish(form)
    return
}

or make testClosure return Void?

class Form {
    var delegate: FormDelegate?

    func testClosure(sender: () -> Void?) {
    }
}

If the closure has one expression swift tries to return that expreeions result. There is great blog post about this feature ( or bug? ) in swift. link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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