Davide
Davide

Reputation: 784

Swift - How can I pass a function with parameters in parameters of a function?

I know that the title sounds complicated, but the question is not.

I have this Swift code:

class MyClass {
let helloWorld: (check: Bool)->()

init(helloWorld: (check: Bool)->()) {
    self.helloWorld = helloWorld
    }
}

let instanceOfMyClass = MyClass(helloWorld: (check: Bool) -> {

})

This gives me an error. What is the correct syntax for the last instruction?

Thanks!

Upvotes: 3

Views: 285

Answers (1)

Antonio
Antonio

Reputation: 72750

You can use this:

let instanceOfMyClass = MyClass(helloWorld: { (check) in println(check) } )

but if the closure is the last argument, you can use the trailing closure syntax, where the closure is written outside of the function (init in your case) parenthesis - which is easier to read:

let instance = MyClass() { (check) in
    println(check)
}

There are other shortcuts to define closures, such as this one:

let instance2 = MyClass() { println($0) }

but I suggest you to read the entire closure chapter in the official swift book.

Note: in my code above replace println(...) with your actual processing

Upvotes: 4

Related Questions