In a multi-clause if statement each clause is separated by a comma.
If you start with a clause where you optionally bind a value with if let, it will be available in the second clause to check if it has the correct value.
This is where commas separating parts of a condition differ from the &&
operator, because while both require every part to be true, either side of an && will not have access to optionally bound values.
Here’s an example in which I create a RandomError.badLuck
and RandomError.unknownData
. The first of these happens because I am just simulating a Result
that can fail by essentially flipping a coin with Bool.random()
. When this value is true, RandomError.badLuck
is thrown. Otherwise a “good job” message is returned.
I’m appending different messages to an array of strings depending on what I find in my Result
. These are then displayed in a scrolling List
I call the log. The following line is an example of an if case let in a multi-clause if statement:
if case let .success(data) = result, case data = goodJob
The data could be anything, although I know the returned string is always going to be the same. In the unlikely event that the string changes later, I will append RandomError.unknownData.localizedDescription
to my log.
I am including logs like this in more of my examples because SwiftUI previews are incapable of showing what gets printed to the console, despite otherwise behaving like a Simulator when in Live Preview mode.
It’s good to be able to test your code without launching a Simulator.
Previews save time and increase the performance of your Mac… when they work.