Swift '_' can only appear in a pattern or on the left side of an assignment

10 min read

In Swift, the underscore character "_" has specific uses and restrictions. It can only appear in certain contexts, namely in patterns or on the left side of an assignment.

  1. Patterns: The "" character in patterns is used as a wildcard or placeholder to ignore a specific value or match any value. It allows you to ignore values that you don't need to use or care about. For example, in a tuple pattern, you can use "" to ignore one or more values:
let (_, secondValue, _) = (1, 2, 3)
print(secondValue) // Outputs: 2

Here, the first and third elements of the tuple are ignored using "_".

  1. Left side of an assignment: "_" can also be used on the left side of an assignment to indicate a value that you don't care about. It is used when you want to ignore the result of a function call or an operation. For example:
let _ = someFunction() // Ignores the result of the function call

In this case, the result of the "someFunction()" call is ignored using "_".

It's important to note that "_" cannot be used as an identifier to name variables, constants, or functions in Swift. It only serves the purpose of a placeholder or wildcard in patterns or on the left side of an assignment.