5

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?

2 Answers 2

3

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?) {
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

that makes a lot of sense. now even the error message make sense. thanks :)
Wow, that's interesting. How does Void differ from Void?, from a conceptual standpoint? Does it?
Void? is optional, just like Int? etc... It can be nil (None) or Void (Some). It main use is in optional chaining method calls to tell whether methods returning Void where ever called.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.