Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: closure as parameter reports error

Tags:

swift

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?

like image 977
warly Avatar asked Sep 30 '22 20:09

warly


2 Answers

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?) {
    }
}
like image 119
Kirsteins Avatar answered Oct 04 '22 04:10

Kirsteins


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

like image 31
mustafa Avatar answered Oct 04 '22 03:10

mustafa