This concise, practical article walks you through some use cases of the underscore character _ in Swift.
Omitting Variable Names in Tuples
Suppose you have a tuple that contains multiple values, but you only care about and want to extract some of them. If this is the case, you can use the underscore character to ignore the values that you don’t need.
Example:
let myTuple = (10, 20, 30)
let (_, mySecondValue, _) = myTuple
print("The second value is \(mySecondValue)")
Output:
The second value is 20
Another example:
let myTuple = (name: "John Doe", age: 35, job: "iOS Developer")
let (_, _, job) = myTuple
print(job)
Output:
iOS Developer
Ignoring Function Parameter Names
When defining a function, we can use the underscore character to indicate that we don’t care about the parameter names, only their values. Later on, you can call this function without argument labels.
Example:
func printNumber(_ number: Int, _ message: String) {
print("\(message) \(number)")
}
printNumber(10, "The number is:")
Output:
The number is: 10
Ignoring Function Return Values
There might be cases where you might call a function that returns a value, but you don’t care about that value. In order to ignore the return value, you can use the underscore character like this:
func printHello() -> String {
print("Hello")
return "World"
}
let _ = printHello()
Output:
Hello