Swift: closing as parameters message

just write a simple quick application, and this error appeared.

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 type '() -> () -> $T2' to type '()' } 

but when I insert the let statement, everything works. Do you know what is going on?

+5
source share
2 answers

The problem is that closures have an automatic return when there is no explicit return. In this case, the return value is Void? , since there is an optional chain. You can fix this by returning as the last statement:

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

or return testClosure Void?

 class Form { var delegate: FormDelegate? func testClosure(sender: () -> Void?) { } } 
+3
source

If there is one expression in the closure, swift tries to return this result expreeions. There is a great blog post about this feature (or bug?) In quick. link

+1
source

Source: https://habr.com/ru/post/1202964/


All Articles