rb612 rb612 - 3 months ago 12
iOS Question

What do _:_: and similar combinations of the colon and underscore mean in Swift?

When reading Swift's documentation, Apple commonly uses

functionName(_:name:)
or something similar. What exactly is this pattern that sometimes is
_:_:
, sometimes just
_:
, and
_:name:
. I think it has to do with parameter shorthand, but I'm not sure, and can't find the explanation in Swift's programming guide. Thank you!

Example:

insert(_:atIndex:)

Answer

The underscore indicates that there is no external parameter name for the function. Apple's Swift Documentation talks about this concept in terms of when you're writing your own functions.

Take the case where you write this function (from the documentation):

func sayHello(to person: String, and anotherPerson: String) -> String { ... }

If you were to use the function you would write the following:

sayHello(to: "Bill", and: "Ted")

The signature for this would be sayHello(to:and:). However, what if we wanted to use the function as sayHello("Bill", "Ted")? How would we indicate that we didn't want an external parameter name? Well that's where the underscore comes in. We could rewrite the function as:

func sayHello(person: String, _ anotherPerson: String) -> String { ... }

Note the first parameter doesn't need the _, but subsequent ones will. The first is inferred to have no parameter name. This makes the method signature for this call sayHello(_:_:) because you as the caller don't have a named parameter.

Update Swift 3.0:

Swift 3.0 treats all parameters equally. The first parameter now requires an underscore to indicate the absense of an external parameter name. In the above example of having sayHello("Bill", "Ted") at the call site, your corresponding function declaration would have to be

func sayHello(_ person: String, _ anotherPerson: String) -> String { ... }

Note the addition of the underscore before the internal parameter name 'person'.

Comments