The ability to write readable, succinct, and expressive code is a valuable skill to possess as a developer.
Consider this function that sets the temperature of an oven:
func setOvenTemperature(temperature: Int) { print("The oven is now set to \(temperature) degrees.") }
We declare the setOvenTemperature
function that takes a single string parameter temperature
and prints the current oven setting to the console.
To call this function we use the following syntax:
setOvenTemperature(temperature: 400) // Prints: Oven is now set to 400 degrees
This works but is a tad repetitive. We have the word temperature twice in a row.
Luckily, Swift gives us argument labels, a feature that can help make our functions read in a sentence-like manner when we call them, while still allowing us to use parameter names in the function body.
The following syntax lets us refer to the parameter name in the body of the function, while using the argument label to refer to the same parameter when calling the function:
func functionName(argumentLabel parameterName: type) { print(parameterName) // Notice that we use the parameter name in the body of the function } // We call the function like so: functionName(argumentLabel: value)
Let’s rewrite the method that sets the oven temperature using argument labels and make it easier to read:
func setOvenTemperature(to temperature: Int) { print("Oven is now set to \(temperature) degrees") } setOvenTemperature(to: 400) // Prints: Oven is now set to 400 degrees
We added an argument label called to
which we will use when calling the function, but within the body of the function we still use the parameter name temperature
.
While the output of this setOvenTemperature
is the same, its syntax setOvenTemperature(to: 400)
reads much more like a sentence and clearly conveys our intent. In the function body, we refer to the parameter name temperature
, which also makes more sense in context.
In practice, you will find that it often makes sense to refer to a parameter by a different name in the body of the function than when calling the function. Swift argument labels enable us to do this!
Instructions
Create a variable named friendsList
of type [String]
and assign it to an empty array.
Write a function named addFriend
. It should take in a parameter called friendName
of type String
, that has an argument label called named
. The function shouldn’t return a value.
In the body of addFriend(named:)
add logic that appends the parameter friendName
to the friendsList
variable.
Call the addFriend(named:)
method three times to add the following friends: “Alice”, “Bob”, and “Cindy”.
Print the contents of the friendsList
variable.