The first parameter has no argument label (using _), so you just pass the value directly. The second parameter uses to as the argument label.
Swift
func add(_ a: Int, to b: Int) -> Int {
return a + b
}
let sum = add(3, to: 5)
print(sum)
If you don't specify an argument label, Swift uses the parameter name as the argument label by default.
Swift
func describe(color: String) {
print("The color is \(color).")
}
describe(color: "blue")
Sample Program
This program defines a function with argument labels person and from. When calling the function, you use these labels to clearly show what each value means.
Swift
func introduce(person name: String, from city: String) {
print("Meet \(name) from \(city).")
}
introduce(person: "Liam", from: "Paris")
OutputSuccess
Important Notes
You can omit argument labels by using _ before the parameter name.
Using clear argument labels makes your code easier to read and understand.
Summary
Argument labels are used when calling functions to clarify what each argument means.
Parameter names are used inside the function to refer to the passed values.
You can have different argument labels and parameter names to make your code clearer.
Practice
(1/5)
1. What is the purpose of an argument label in a Swift function?
easy
A. To store the return value of the function
B. To define the variable type inside the function
C. To clarify the meaning of each argument when calling the function
D. To create a new function inside another function
Solution
Step 1: Understand argument labels
Argument labels are used outside the function when calling it to make the call clearer.
Step 2: Differentiate from parameter names
Parameter names are used inside the function, but argument labels help the caller understand what each value means.
Final Answer:
To clarify the meaning of each argument when calling the function -> Option C
Quick Check:
Argument label = clarify call [OK]
Hint: Argument labels clarify calls, parameter names work inside [OK]
Common Mistakes:
Confusing argument labels with parameter names
Thinking argument labels define variable types
Assuming argument labels store return values
2. Which of the following is the correct way to declare a function with an argument label from and a parameter name start of type Int?
easy
A. func move(from: start Int) { }
B. func move(from start: Int) { }
C. func move(start from: Int) { }
D. func move(Int from start) { }
Solution
Step 1: Recall Swift function syntax for labels
The syntax is: func name(argumentLabel parameterName: Type) { }.