Are Swift 4 custom argument labels ALWAYS required or just for disambiguation of functions?

Viewed 62

This question is similar to Swift 4 custom argument labels - required? but more specific. I came across that question when researching a problem caused by changing from a var (requiring no parameter) to a func (requiring a parameter) but missed changing all references. I have created a playground that contradicts the claim made in a subsequent edit to that question: "question is incorrect, as custom labels are mandatory" My question is: how to correctly express what I observed, as demonstrated below:

class SomeTest {
    static func someParam(p1: String?) -> String? {
        return "hello \(p1 ?? "nothing")"
    }

    // Uncommenting the following causes error at let funny
    //    static func someParam(p2: String?) -> String? {
    //        return "hello \(p2 ?? "nothing")"
    //    }

    static func doIt() {
        let funny = someParam // ignoring the argument label is ok if there is no ambiguity

        funny("thing") // and can be used without

        someParam(p1: "thing2") // must have argument label
    }
}

SomeTest.doIt()
1 Answers

If you have both someParam functions (each with a differently named parameter), then the line:

let funny = someParam

no longer works since it isn't known which of the two someParam functions you are referring to. This is solved by providing an unambiguous name:

let funny = someParam(p1:) // or someParam(p2:)

Note that funny has a type of (String?) -> String?. Both someParam functions have that same type. This is why you need to provide more detail to disambiguate the two. The parameter names don't change the function type.

When directly calling a function you must provide the full function name which includes any named parameter labels.

But when you create a closure variable and assign it the value of a function, you don't need to provide more than the base name of the function if that name is unambiguous in the given context.

Related