Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Trailing Closure Syntax

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?

like image 524
Kosmetika Avatar asked Jun 16 '14 17:06

Kosmetika


People also ask

How do you declare a closure in Swift?

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.

What is $0 and $1 in Swift?

$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.

What is Clouser in Swift?

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.

What does @escaping mean in Swift?

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”.


1 Answers

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)")
}
like image 179
Christian Dietrich Avatar answered Nov 12 '22 00:11

Christian Dietrich