0
0
Swiftprogramming~5 mins

Omitting argument labels with _ in Swift

Choose your learning style9 modes available
Introduction

Sometimes you want to call a function without writing the argument label every time. Using _ lets you skip the label for cleaner calls.

When the argument label is obvious and repeating it feels unnecessary.
When you want to make function calls shorter and easier to read.
When working with functions that have many parameters and you want simpler calls.
When you want to match a function signature that requires no labels for arguments.
Syntax
Swift
func functionName(_ parameterName: Type) {
    // function body
}

The underscore _ before a parameter name means you don't have to write the label when calling the function.

This only affects how you call the function, not how you use the parameter inside the function.

Examples
You call greet without writing the label name: because of the _.
Swift
func greet(_ name: String) {
    print("Hello, \(name)!")
}
greet("Alice")
Both parameters omit labels, so you just pass values separated by commas.
Swift
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
let sum = add(3, 5)
print(sum)
The first parameter has a label factor1, the second omits it with _.
Swift
func multiply(factor1 a: Int, _ b: Int) -> Int {
    return a * b
}
let result = multiply(factor1: 4, 5)
print(result)
Sample Program

This program defines a function that greets a person. The argument label is omitted, so you just pass the name directly.

Swift
func sayHello(_ person: String) {
    print("Hi, \(person)!")
}
sayHello("Bob")
OutputSuccess
Important Notes

Using _ can make your code cleaner but be careful not to lose clarity.

Omitting labels is common in Swift's standard library functions like print().

Summary

Use _ to skip argument labels when calling functions.

This makes function calls shorter and sometimes easier to read.

Inside the function, you still use the parameter name as usual.