Sling Academy
Home/Swift/The Underscore Character (_) in Swift

The Underscore Character (_) in Swift

Last updated: February 22, 2023

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

Previous Article: Defining Functions in Swift

Series: Swift Basics

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)