swift - How to have an optional trailing closure? -
i'm trying write function can call trailing closure syntax so:
func hello( message: string, closure: (( msg: string ) -> void)?) { println( "called hello with: \(message)" ); closure?( msg: message ); }
i expect able call function closure:
hello( "abc" ) { msg in let = "def"; println("called callback with: \(msg) , i've got: \(a)"); };
and without closure, since it's optional:
hello( "abc" )
the latter doesn't work. says can't call hello argument list of (string).
i'm using xcode 6.3.2 , tested code within playground.
i'm not sure you've got definition of optional entirely correct. doesn't mean don't need supply value closure
argument; means closure
can either have value (of closure in case) or nil
. therefore, if wanted call hello
without providing closure write:
hello("abc", nil)
however, can achieve you're after using default parameter values (i'd recommend have @ the swift programming guide: functions). function be:
// note `= 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) }
Comments
Post a Comment