Fun with wildcards

Do something multiple times

One fun way to use the wildcard pattern is within the definition of a for loop:

for _ in 1...3 { print("hi") // 3 times

}

This code performs its action three times. The underscore _ means that you don’t care to use each value from the sequence. If you ever find yourself needing to repeat an action, this is a clean way to write the code.

Validate that an optional exists

let user: String? = "Bob" guard let _ = user else {

print("There is no user.") fatalError()

}

print("User exists, but identity not needed.") // Printed!

In this code, you check to make sure user has a value. You use the underscore to indicate that, right now, you don’t care what value it contains.

Even though you can do something, doesn’t mean you should. The best way to validate an optional where you don’t care about the value is like so:

guard user != nil else { print("There is no user.") fatalError()

}

Here, user != nil does the same thing as let _ = user but the intent is clearer when you read the code.

Organize an if-else-if

struct Rectangle { let width: Int let height: Int let color: String

}

let view = Rectangle(width: 15, height: 60, color: "Green") switch view {

case _ where view.height < 50: print("View shorter than 50 units")

case _ where view.width > 20:

print("View at least 50 tall, & more than 20 wide") case _ where view.color == "Green":

print("View at least 50 tall, at most 20 wide, & green") // Printed! default:

print("This view can't be described by this example")

}

You could write this code as a chain of if statements. By using the switch statement, it is clear that each condition is a case. Notice that each case uses an underscore with a qualifying where clause.

results matching ""

    No results matching ""