← Articles

Using double argument labels in Swift functions

Swift allows for double labelling your function arguments. Here's how and why.

Did you know that you can use two labels for function arguments in Swift? No? I didn't really realise how flexible it was until now either.

Why do double labels even exist?

Say you have some system that is used to give users awards.

You want to implement a function:

Plain text
func assignAward() {}

This function will need a parameter for passing in the user. Logically we would call this parameter user, or something akin to that, but this function declaration is not really readable is it?

Plain text
func assignAward(user: String) {}

The function name read-aloud would be "Assign award user ..." .
This is okay, but Swift provided a better way for when you are in need of distinguishing between how your parameter should be labeled outside of the function, when it is called, and inside of the function, when you use the value.

And it is actually easy.

Using double labels

Let's look at our function from earlier again. It would be much better if we could use the label "to", since then our function call would read like this "Assign award to".
But inside our function it would be unwise to call our variable "to", as this is really not descriptive and helpful. Even more so, if you have cases where you would want the label to be "for". (See later :) )

This new sentence "Assign award to" combined with still being called user within the function, would be written as:

Plain text
func assignAward(to user: String) {}

// is called as

assignAward(to: "Stefan B.")

As you can see, this is super simple, we just write the name of how we would label it outside the function first and then as the second label we declare the one for use within the function itself.

As a bonus, if you are using Xcode 26 and above, I have brought you a little example within the Playground macro. You can use it in any file by importing Playgrounds. This example shows the example from above, as well as one with for as the outer label. Test it, in your IDE to see what happens :)

Plain text
#Playground {
	func assignAward(to user: String) {
		print("Award was assigned to \(user)")
	}
	
	func requestAccess(for client: String) {
		print("Access was requested for \(client)")
	}
	
	func thisIsADemonstration(outerLabel innerLabel: String) {
		print(innerLabel)
	}
	
	assignAward(to: "Fr. Frank")
	
	requestAccess(for: "Nils W.")
	
	thisIsADemonstration(outerLabel: "Hello I am under the water")
}

Thank you for reading. Happy double labelling!

Comments

Loading comments…