1
votes

Can a Swift func/closure signature specify that default parameter values are provided?

A highly simplified version of what I'm trying to do is this:

struct L {
    typealias W = ((String, String, String) -> Void)
    static func w(_ w:String, _ t:String = "t", _ f:String = "f") {
        let line = w + t + f
        print(line)
    }
    static let ws:[W] = [L.w, L.w]
}

L.ws[0]("sue", "seven", "red")
L.ws[0]("bill")

The error I get at the "bill" call is: error: missing argument for parameter #2 in call

I tried changing the typealias line to:

typealias W = ((String, String = "t", String = "f") -> Void)

But that gives me an error at the typealias line: error: default argument not permitted in a tuple type

This does not help either:

typealias W = ((String, String?, String?) -> Void)

1
Swift does not automatically generate thunks for decorating functions with their default arguments. Even though your func w has defaulted arguments, its type is still (String, String, String) -> Void - Alexander
What exactly are you trying achieve? - Alexander
@Alexander Thanks for helping with valuable input, but I prefer not to enter into an XY problem discussion on this question/answer. - Jeff

1 Answers

2
votes

The following radar:

Was marked as fixed in the following validation test:

// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// http://www.openradar.me/18041799
// https://gist.github.com/stigi/336a9851cd80fdef22ed
func a(b: Int = 0) {
}
let c = a
c() // expected-error {{missing argument for parameter #1 in call}}

Based on the validation test above (particularly the expected error), I believe calling a function via a stored reference to it (e.g. L.ws[0] in your example) will not allow omitting arguments even if the function pointed to supplies default parameter values for these omitted arguments.

The type of the c stored closure (/function reference) above will be inferred to as (Int) -> (), and will contain no information regarding default parameter values. When attempting to call c as if it were a closure/function pointer of type () - > (), the missing argument error will be prompted without any possibility of tapping into the compiler magic that works when directly calling a function (not via a stored reference/closure to it!) that, in itself, allows omitting arguments for parameters with default values.