Swift - Trailing Closure Syntax

11,886

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)")
}
Share:
11,886
Kosmetika
Author by

Kosmetika

#SOreadytohelp

Updated on June 04, 2022

Comments

  • Kosmetika
    Kosmetika about 2 years

    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?

  • Kosmetika
    Kosmetika about 10 years
    I have one more question, this resolve(name: name) throws an error use of unresolved identifier 'name'.. how to pass arguments in callback call?
  • Christian Dietrich
    Christian Dietrich about 10 years
    hi i dont get that. can you share the code that fails?
  • jmg
    jmg over 6 years
    I have a question... In the first code example that you provided above, you have "{(name: String) in". What's the semantic meaning of "in" when used in this context?
  • Christian Dietrich
    Christian Dietrich over 6 years
    In is the separator between parameters and statements