Swift
Programming
Underscores
Swift Language Features
Swift Development

Why do I need underscores in swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Swift, Apple's powerful and intuitive programming language for macOS, iOS, watchOS, and tvOS, often introduces developers to unique syntax and conventions designed to create safe and expressive code. One such convention is the use of underscores (_) in various contexts. This article will delve into why underscores are used in Swift, exploring their significance with technical explanations and examples.

Key Uses of Underscores in Swift

Underscores in Swift serve multiple purposes, from acting as wildcards to improving code readability. Here, we'll explore some of the primary uses.

Ignoring Values

In Swift, you might encounter situations where a value is returned by a function, but you don't need to use it. In such cases, underscores allow you to ignore these values. Here's an example:

swift
1let numbers = [1, 2, 3, 4, 5]
2
3for _ in numbers {
4    // Code that needs to run for each number without using the number itself
5    print("Hello, World!")
6}

This is useful when the value isn't needed to execute the loop. The underscore signifies an intentional disregard for that particular value.

Discarding Function Parameters

Swift functions can have parameters that are not used within the function body. To signify this, you can use underscores to discard these parameters. For instance:

swift
1func fetchUserData(_, username: String) {
2    // Only use the username parameter
3    print("Fetching data for \(username)")
4}

This typically happens in closures where unnecessary parameters are required due to the function signature but aren't used. By convention, using an underscore makes it clear that these parameters are ignored.

Omitting External Parameter Names

Swift allows you to specify both internal and external names for parameters in functions and methods. Sometimes, you might want to suppress the external parameter name to make a function call more readable. For this, you can use an underscore:

swift
1func divide(_ a: Int, by b: Int) -> Int {
2    return a / b
3}
4
5let result = divide(10, by: 2)

Here, using _ means a doesn't need an external name, allowing a more fluent syntax when calling divide.

Pattern Matching and Wildcards

In Swift's powerful pattern matching syntax, underscores can act as wildcards to denote any value without caring about what it is. For example, when switching over an enumeration or using if case:

swift
1enum CompassPoint {
2    case north
3    case south
4    case east
5    case west
6}
7
8let direction = CompassPoint.north
9
10switch direction {
11case .north:
12    print("Heading North")
13case .south:
14    print("Heading South")
15case .east:
16    print("Heading East")
17case .west:
18    print("Heading West")
19}

If we do not care about all cases we can use _:

swift
1switch direction {
2case .north:
3    print("Heading North")
4default:
5    print("Not heading North")
6}

Readability in Large Numbers

For better readability, Swift allows underscores to be used as separators in numeric literals, without affecting their actual value:

swift
let socialSecurityNumber = 123_45_6789
let largeNumber = 1_000_000_000

This practice helps improve the readability of large numbers, aligning them with customary formatting (e.g., thousands, millions) and enhancing the developer's ability to quickly understand the code.

Summary

The varied uses of underscores in Swift contribute to more concise, readable, and intention-revealing code. Below is a table summarizing the key reasons and uses for underscores in Swift.

PurposeDescription
Ignoring ValuesUsed to discard unneeded variable values, e.g., in loops and function calls.
Discarding ParametersOmits unused parameters or variables within functions or closures, signaling they are not important.
Omitting External NamesSuppresses external parameter names for cleaner and more readable function calls.
Pattern MatchingUtilized as wildcards in pattern matching, allowing for matching without specifying a value.
Readable NumbersUsed as separators in numeric literals, improving readability without affecting value.

By utilizing underscores strategically, Swift developers can maintain clean and expressive code, aligning with Swift’s design philosophy. Understanding these nuances can greatly enhance one’s proficiency and efficiency in writing Swift programs.


Course illustration
Course illustration

All Rights Reserved.