4

I would like to use default values for arguments of a lambda, such as:

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 a good work around for this? Will that be possible in future versions?

db0
  • 3,689
  • 3
  • 23
  • 26

2 Answers2

3

I can't speak to whether or not this will ever be possible in the way you've attempted, but it looks like you can get around that error by using a nested function instead.

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

    return lambda()
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • 1
    That's what I used to do, but it's no longer possible with the new version beta 6: http://stackoverflow.com/questions/25474436/cannot-reference-a-local-function-error-in-xcode-6-beta-6 – db0 Aug 25 '14 at 14:46
  • 1
    @db0 Can you show what exactly you're trying to do that doesn't work like this? The code I've provided works fine on beta 6. – Mick MacCallum Aug 25 '14 at 14:51
  • 1
    It's not a global function, it's a function within a class, which gets this (pretty explicit) error, only since beta6: "Cannot reference a local function from another local function" – db0 Aug 25 '14 at 15:11
3

This seems to be very buggy even in Xcode 6.0.1. The following code crashes 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

As for the error you get from your code, from the outside, it seems like an arbitrary limitation. It's possibly due to how methods are implemented under the hood in Swift but that's just a guess.

Sebastien Martin
  • 1,341
  • 11
  • 25