0
0
Swiftprogramming~5 mins

Argument labels and parameter names in Swift

Choose your learning style9 modes available
Introduction

Argument labels and parameter names help make your function calls clear and easy to read, like giving names to the pieces of information you pass in.

When you want your function calls to read like simple sentences.
When you want to avoid confusion about what each value means in a function call.
When you want to use different names inside the function than outside.
When you want to make your code easier for others (or yourself) to understand later.
Syntax
Swift
func functionName(argumentLabel parameterName: Type) {
    // function body
}

The argument label is used when calling the function.

The parameter name is used inside the function.

Examples
Here, person is the argument label used when calling, and name is the parameter name used inside the function.
Swift
func greet(person name: String) {
    print("Hello, \(name)!")
}
greet(person: "Anna")
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.