As a developer, being able to write readable, succinct, and expressive code is a valuable skill. So, we use argument labels for this purpose in Swift.
Consider the following function for controlling the temperature of an AC:
func changeAcTemperature(temperature: Int) {
print("The temperature in the room has been raised to \(temperature) degrees.");
}
The changeAcTemperature
function, which takes a single Int
parameter temperature
and prints the current room temperature to the console, is declared.
We use the following syntax to call this function:
changeAcTemperature(temperature: 27);
// Prints: The temperature in the room has been raised to 27 degrees.
This works, but it’s a little boring. The word temperature appears twice in a row.
Thankfully, Swift provides argument labels, a feature that allows us to call our functions in a sentence-like manner while still allowing us to use parameter names in the body.
The following syntax allows us to refer to the parameter name in the body of the function while also referring to the same parameter when calling the function with the argument label:
func functionName(argumentLabel parameterName: type) {
print(parameterName); // It's important to note that we use the parameter name in the function's body.
}
// This is how we call the function:
functionName(argumentLabel: value);
To make it easier to read, let’s rewrite the method that change the AC temperature using argument labels:
func changeAcTemperature(to temperature: Int) {
print("The temperature in the room has been raised to \(temperature) degrees.");
}
changeAcTemperature(to: 27);
// Prints: Oven is now set to 400 degrees
We added an argument label called to
, which we will use when calling the function, but we will continue to use the parameter name temperature
within the body of the function.
While the output of this changeAcTemperature
is the same, the syntax changeAcTemperature(to: 27)
reads more like a sentence and expresses our intent more clearly. We use the parameter name temperature
in the function body, which makes more sense in context.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.