swift where with an example of the matching pattern

  • 2020-06-01 11:07:43
  • OfStack

swift where with an example of the matching pattern

Preface:

Among the many new features that Swift offers to Objective-C programmers is a feature that disguises itself as a boring old man, but has great potential to elegantly solve the problem of the "scourge pyramid." Obviously the feature I'm talking about is the switch statement. For many Objective-C programmers, the switch statement is clunky and has few advantages over multiple if statements, except that it's fun to use on Duff's Device.

1. Basic use

In Swift, the switch statement case can be followed by where to restrict the condition


let point = (3,3)
switch point{
case let (x,y) where x == y:
  print("It's on the line x == y!")
case let (x,y) where x == -y:
  print("It's on the line x == -y!")
case let (x,y):
  print("It's just an ordinary point.")
  print("The point is ( \(x) , \(y) )")
}

2. Use the if-case-where statement instead of the switch statement


let age = 19
switch age{
case 10...19:
  print("You're a teenager.")
default:
  print("You're not a teenager.")
}


if case 10...19 = age{
  print("You're a teenager.")
}

if case 10...19 = age where age >= 18{
  print("You're a teenager and in a college!")
}

Note: the case condition must precede "="

After swift 3.0, "where" after if case is replaced by ","

3. Combination of if-case and tuples (tuple unpacking)


let vector = (4,0)
if case ( let x , 0 ) = vector where x > 2 && x < 5{
  print("It's the vector!")
}

4. case-where is used in combination with circulation


for i in 1...100{
  if i%3 == 0{
    print(i)
  }
}

for case let i in 1...100 where i % 3 == 0{
  print(i)
}

The use of case restrictions can greatly reduce the amount of code, is very easy to use, is a major feature of swift language, a good grasp can write very elegant and concise code

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: