2

I'm trying to write a function that I can call with trailing closure syntax like so:

func hello( message: String, closure: (( msg: String ) -> Void)?) {

   println( "called hello with: \(message)" );

   closure?( msg: message );

}

I would expect to be able to call this function with a closure:

hello( "abc" ) { msg in

    let a = "def";

    println("Called callback with: \(msg) and I've got: \(a)");

};

And also without the closure, since it's optional:

hello( "abc" )

The latter doesn't work. It says I can't call hello with an argument list of (String).

I'm using XCode 6.3.2 and I tested this code within a playground.

1 Answer 1

4

I'm not sure you've got your definition of optional entirely correct. It doesn't mean you don't need to supply a value for the closure argument; it means closure can either have a value (of a closure in your case) or be nil. Therefore, if you wanted to call hello without providing a closure you would write:

hello("abc", nil)

However, you can achieve what you're after using default parameter values (I'd recommend you have a look at The Swift Programming Guide: Functions). Your function would be:

// Note the `= nil`:
func hello(message: String, closure: ((msg: String ) -> Void)? = nil) {
    println("called hello with: \(message)")

    closure?(msg: message)
}


// Example usage:
hello("abc")
hello("abc") { println($0) }
Sign up to request clarification or add additional context in comments.

1 Comment

That makes perfect sense, thank you. I was wrongly assuming the trailing closure would automatically be assumed to be nil if not provided.

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.