I'm diving into Swift lang by Apple and have some problems using the trailing closure syntax, example:
func test(txt: String, resolve: (name: String) -> Void) {
resolve(name: "Dodo")
}
// Errors here complaining on resolve param
test("hello", (name: String) {
println("callback")
})
How to fix it?
Swift Closure Declaration parameters - any value passed to closure. returnType - specifies the type of value returned by the closure. in (optional) - used to separate parameters/returnType from closure body.
$0 and $1 are closure's first and second Shorthand Argument Names (SAN for short) or implicit parameter names, if you like. The shorthand argument names are automatically provided by Swift. The first argument is referenced by $0 , the second argument is referenced by $1 , the third one by $2 , and so on.
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
In Swift, a closure marked with @escaping means the closure can outlive the scope of the block of code it is passed into. In a sense, @escaping tells the closure to “stay up even after the surrounding function is gone”.
you have the wrong closure syntax
test("hello", {(name: String) in
println("callback")
})
or
test("hello", {
println("callback: \($0)")
})
or
test("hello") {(name: String) in
println("callback")
}
or
test("hello") {
println("callback: \($0)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With