Control flow of Swift notes

  • 2020-05-10 22:59:34
  • OfStack

The control flow is basically the same. Here are a few interesting points.

switch

Break

The text is No Implicit Fallthrough. There is no implicit penetration. Among them, Implicit is a frequently used word. In Chinese, it means "implicit, implied and reserved". In Swift it usually means default processing. For example, the implicit penetration here refers to the traditional situation where multiple case would go from top to bottom without break. Another example is implicitly unwrapped optionals, which implicitly resolves the optional type, and by default unpacks without having to go through it manually! Unpack.

Back to the switch problem, take a look at the following code:


let anotherCharacter: Character = "a"

switch anotherCharacter {
case "a":
  println("The letter a")
case "A":
  println("The letter A")
default:
  println("Not the letter A")
}

You can see that even though it matches case "a", it pops out after the current case ends, without continuing the execution. case can be implemented via fallthrough if you want to continue through to the bottom.

Tuple

We can use the meta-ancestor (tuple) in switch for matching. All values are denoted by _. For example, here is an example to determine what region the coordinates belong to:


let somePoint = (1, 1)

switch somePoint {
case (0, 0):  //  Located in the far point 
  println("(0, 0) is at the origin")
case (_, 0):  // x Is any value, y for 0 In which the  X  On the shaft 
  println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):  // y Is any value, x for 0 In which the  Y  On the shaft 
  println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2): //  It's centered at the origin 4 Inside the square. 
  println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
  println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}

// "(1, 1) is inside the box"

If you want to use this value in case, you can use the value binding (value bindings) to:


let somePoint = (0, 1)

switch somePoint {
case (0, 0):
  println("(0, 0) is at the origin")
case (let x, 0):
  println("x is \(x)")
case (0, let y):
  println("y is \(y)")
default:
  println("default")
}

Where

Parameters can be matched with where in case. For example, if we want to print y=x or y= -x, we can use switch to do the following:


let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
  println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
  println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
  println("(\(x), \(y)) is just some arbitrary point")
}
// "(1, -1) is on the line x == -y " 

Control Transfer Statements

Swift has four control transfer states:

continue - for loop, directly carry out the next loop iteration. Tell the loop body: I'm done with this loop.
break - for control flow (loop + switch), directly ends the entire control flow. In loop it jumps out of the current loop, in switch it jumps out of the current switch. If there's an case in switch that you really don't want to do anything with, you can just add break to it and ignore it.
fallthrough - in switch, lead the code to the next case instead of jumping out of switch by default.
Used in the return - function
other

Here's an interesting thing to see: Swift Cheat Sheet, which is a pure snippet of code that you can look at if you suddenly short-circuited and forgot the syntax.

For example, the Control Flow section has the following code, which basically covers all the points:


// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
  if value == 1 {
    println("One!")
  } else {
    println("Not one!")
  }
}

// for loop (dictionary)
var dict = [
  "name": "Steve Jobs",
  "title": "CEO",
  "company": "Apple"
]
for (key, value) in dict {
  println("\(key): \(value)")
}

// for loop (range)
for i in -1...1 { // [-1, 0, 1]
  println(i)
}
// use .. to exclude the last number

// for loop (ignoring the current value of the range on each iteration of the loop)
for _ in 1...3 {
  // Do something three times.
}

// while loop
var i = 1
while i < 1000 {
  i *= 2
}

// do-while loop
do {
  println("hello")
} while 1 == 2

// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
  let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
  let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
  let vegetableComment = "Is it a spicy \(x)?"
default: // required (in order to cover all possible input)
  let vegetableComment = "Everything tastes good in soup."
}

// Switch to validate plist content
let city:Dictionary<String, AnyObject> = [
  "name" : "Qingdao",
  "population" : 2_721_000,
  "abbr" : "QD"
]
switch (city["name"], city["population"], city["abbr"]) {
  case (.Some(let cityName as NSString),
    .Some(let pop as NSNumber),
    .Some(let abbr as NSString))
  where abbr.length == 2:
    println("City Name: \(cityName) | Abbr.:\(abbr) Population: \(pop)")
  default:
    println("Not a valid city")
}

That's all for this article, I hope you enjoy it.


Related articles: