Swift: use default arguments in lambda

I would like to use default values ​​for lambda arguments, for example:

func lambdaArgumentTest() -> String {
  let lambda = { (optString: String = "") -> String in optString }
  return lambda()
}

But the compiler seems to state that this is not possible:

Default argument is only permitted for a non-curried function parameter

Is there any good job for this? Will this be possible in future versions?

+4
source share
2 answers

I can’t talk about whether this will ever be possible in the form in which you tried, but it looks like you can get around this error by using a nested function instead.

func lambdaArgumentTest() -> String {
    func lambda(optString: String = "") -> String {
        return optString
    }

    return lambda()
}
+3
source

This seems to be very difficult even in Xcode 6.0.1. The following code splits the Playground 100% of the time:

func test(_ a: Int = 0) -> Int {
    return 100 + a;
}

let test2 = test

test()   // returns 100
test(21) // returns 121

// test2()  // crashes playground if uncommented

, , , . , , Swift, .

+2

All Articles