Why do I need underscores in Swift?


In Swift, underscores have many different uses for a different purposes. Here are some examples.

  • Ignore unnecessary loop variables or return values.

  • Absence of identifiers for external parameters in function calls.

  • Even if they were initially specified as constants, making variables changeable.

  • Ignoring tuple components or using discard values when managing errors.

To Ignore a Value

To ignore a value that a function or method returns in Swift, use an underscore. You could compose something like this, for instance, if you only worry about an operation's success or failure. This is the most common case you use in your code.

Syntax

if _ = someFunction() {
   // do something if the function succeeds
} else {
   // do something if the function failed
}

Example

In this example, the greetingMessage() function returns a string value, but we're ignoring it by using an underscore in the conditional statement. Instead, we're just checking whether the function succeeded or failed based on whether it returned a value or not.

import Foundation
func greetingMessage(fullName: String) -> String? {
   return "Good morning, \(fullName)"
}
if let _ = greetingMessage(fullName: "Alex Murphy") {
   print("Function successfully executed.")
} else {
   print("Function failed to execute.")
}

Output

Function successfully executed.

To Omit External Parameter Names

In Swift, you can use an underscore to omit the external parameter names for a function or method. This concept is widely used in iOS applications. For example, if you have a function like this −

syntax

func doSomething(_ value: Int) {
   // do something with the value
}

Example

In this example, the greetingMessage() function takes a string parameter named fullName, but we're omitting the external parameter name by using an underscore in the function declaration. When we call the function, we just provide a string value without specifying the parameter name.

import Foundation
func greetingMessage(_ fullName: String) -> String? {
   return "Good morning, \(fullName)"
}
if let _ = greetingMessage("Alex Murphy") {
   print("Function successfully executed.")
} else {
   print("Function failed to execute.")
}

Output

Function successfully executed.

To Make a Variable Mutable

In Swift, you can use an underscore to make a variable mutable. For example, if you have a constant like this −

Example

In this example, we're creating a mutable variable called x by adding an underscore before its name. We're initializing it with the value of x, which is a constant. We're then adding 10 to x and printing its value. Since _x is mutable, we can modify its value even though it was originally derived from a constant value.

import Foundation
let x = 42
var _x = x
_x += 10
print(_x)

Output

52

Ignoring a Loop Variable

You can ignore the variable while performing anything using a loop.

Example

In this example, we're using an underscore to ignore the loop variable in a for loop. We're simply iterating over the numbers array and incrementing the sum variable for each element in the array. Since we don't need to use the loop variable (which would normally be an integer index), we can use an underscore to indicate that we're ignoring it.

import Foundation
let numbers = [1, 2, 3, 4, 5]
var sum = 0
for _ in numbers {
   sum += 1
}
print("Number of elements: \(sum)")

Output

Number of elements: 5

Ignoring Part of a Tuple

A tuple contains multiple values together. In order to use the specific values, you can ignore the part of a tuple.

Example

In this example, we're using an underscore to ignore the y component of a tuple. We're then using pattern matching to extract the x and z components of the tuple and assign them to local variables. Since we don't need the y component, we can use an underscore to ignore it.

import Foundation
let point = (x: 10, y: 20, z: 30)
let (x, _, z) = point
print("All values: \(point)")
print("x: \(x), z: \(z)")

Output

All values: (x: 10, y: 20, z: 30)
x: 10, z: 30

Ignoring a Throw Value

While you use the do-catch statement to manage the errors in your code, you can ignore the thrown value.

Example

In this example, we're using an underscore to ignore the error that might be thrown by the doSomething() function. We're calling the function inside a do block and using a catch block to handle any errors that might be thrown. Since we don't care about the specific error value, we can use an underscore to ignore it and just print a generic failure message.

import Foundation
func doSomething() throws -> Int {
   // do something that might throw an error
   return 42
}
do {
   let result = try doSomething()
   print("Success: \(result)")
} catch _ {
   print("Failure")
}

Output

Success: 42

When Using Underscores in Swift, Keep the Following Extra Considerations in Mind

  • Underscoring is not required. Code can frequently be written without underlining and still produce the same results. However, using underscores can help you write more legible and succinct code.

  • If you use underscores overly or improperly, your code may become more difficult to comprehend. For instance, using an underscore to hide a crucial mistake number in a function call may result in errors or strange behavior.

  • Underscores can have different meanings based on the situation in which they are used. For instance, an underscore used in a switch expression as a wildcard pattern and one used to ignore a loop variable have distinct meanings.

  • Underscores can be combined with other language features to create powerful abstractions. For example, combining underscores with closure syntax can create very concise and readable code.

  • Underscores are not specific to Swift and are used in many other programming languages for similar purposes.

Conclusion

It is possible to make your code more concise and easier to read by using underscores, especially when you don't need to use a specific value or parameter name. It's important to use underscores judiciously and avoid using them in a way that might complicate your code. Using underscores in your code should make the code clearer and easier to maintain, as is the case with any language feature.

Updated on: 04-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements