'Multiple right if-conditions Swift
pretty simple question, hard solution, at least for me. How I can do the code of an if and else if statement when the conditions are both time right? like I do a variable x and y and I check if x is 5 then it says something but it says something else when y is 5 either, now the point is what if both are 5? bc after one if statement it skips the other if/else if. thanks for ur solutions!
Solution 1:[1]
Swift actually has a very powerful switch statement that you can use to check the value of multiple variables. Consider this code:
var x: Int = 3
var y: Int = 5
switch (x, y) {
case (1, 4):
print("x == 1 and y == 4")
case (3, 5):
print("x == 3 and y == 5")
case (5, 5):
print("x and y are both 5")
case (5, let y) where y > 5:
print("x == 5. Y > 5")
case (5, _):
print("x == 5. y == some value we didn't test for.")
case (_, 5):
print("y == 5. x == some value we didn't test for.")
default:
print("Dunno")
}
It works by combining multiple values into a tuple, and then switching on the tuple. The cases inside the switch statement can do all kinds of different tests on the values of the tuple.
That code prints:
x == 3 and y == 5
With the values I assigned to it. The "_" bit means "don't care" for that part of the tuple. The "let y" means "Take the second value in the switch statement and assign it to a local variable y that only exists in this case." You can then add a "where" clause that lets you do more complex tests, like my "where y > 5" example.
Edit:
As Jessy pointed out in their comment, binding a value to y with let y in my case (5, let y) where y > 5: example is pointless, since the switch statement is already operating on a variable named y. It would work just as well as case (5, _) where y > 5: in that particular example.
However, if the switch statement was a switch on constant values (e.g. switch (x, 7)) or on a tuple variable:
let aTuple = (5,7)
switch aTuple {
case (5, let y) where y > 5:
...
Then binding the second value to a variable would be useful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
