3

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!

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! And thanks for the link too. I wasn't able to find it.
You're welcome. Glad to know my answer helped you ;-)
when there are no more parameters after taking out the closure, you can omit the parentheses: MyClass { println($0) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.