Underscores in Swift
In Swift, underscores (_) serve various purposes, and lets see some of the common uses of underscores in Swift programming language:
1. Variable Names and Labels: Used to create more readable variable names by separating words. For example:
let myVariable = 10_00
let user_name = "John"
2. Function Parameters: Used to label unnamed parameters in functions. For example:
func greet(_ name: String) {
print("Hello, \(name)!")
}
greet("Alice")
3. Omitting External Parameter Names: When defining functions, underscores can be used to omit external parameter names. This makes the function call cleaner.
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let result = add(5, 3)
4. Wildcard Pattern: Used as a wildcard pattern when you don't need to use the value. For example, in a switch statement:
let point = (2, 3)
switch point {
case (_, 0):
print("On the x-axis")
case (0, _):
print("On the y-axis")
default:
print("Somewhere else")
}
5. Placeholder in Closures: When using closures, you can use underscores as placeholders for parameters if you don't need to use them.
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce(0) { $0 + _ }
These are some of the common uses of underscores in Swift. They contribute to the clarity and conciseness of Swift code.