Dov
Dov

Reputation: 16156

Why can't I use the shorthand argument names in this default parameter value?

The following code isn't compiling, though it seems to me it should:

public typealias ACallback = (first: [Int], second: String, third: String, fourth: CustomType) -> [Int];

public func doSomething(callback: ACallback = { $0 } {
    ...
}

I get an error on the function declaration's line:

'(first: [Int], second: String, third: String, fourth: CustomType)' is not convertible to '[Int]'

When I declare the function like so, it works:

public fund doSomething(callback: ACallback = { first, _, _, _ in first } {

It also makes no difference if I replace the ACallback with the same definition inline.

Upvotes: 0

Views: 74

Answers (2)

dangnabit
dangnabit

Reputation: 664

Although the question isn't a duplicate—the answer to this question seems to explain this behaviour.

To answer the question in your comment—you could redefine the type as a structure or a class (whatever is suitable) and be able to refer to the arguments as properties (instead of as position numbers in the tuple).

Upvotes: 1

ikesyo
ikesyo

Reputation: 436

callback: ACallback = { $0.0 } should be OK, I think. As the error describes, $0 means a tuple of entire parameter list of that closure here.

Upvotes: 1

Related Questions