简体   繁体   English

Swift:由于参数关闭而报告错误

[英]Swift: closure as parameter reports error

just writing a simple swift app and this error came up. 只是编写一个简单的Swift应用程序,就会出现此错误。

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. 但是当我插入let语句时,一切正常。 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? 在这种情况下,返回值为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? 或使testClosure返回Void?

class Form {
    var delegate: FormDelegate?

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

If the closure has one expression swift tries to return that expreeions result. 如果闭包中有一个表达式,则swift尝试返回该乘方结果。 There is great blog post about this feature ( or bug? ) in swift. 迅速有很多关于此功能的博客文章(或bug?)。 link 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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