The where keyword in swift and some weird stuff

The where keyword in Swift syntax has the same function as where in SQL, that is, additional conditional judgment.


1. Use where when traversing the collection, execute the code block when the condition is true, and do not execute the code block when it is false.

case let x where x > 3:


2、for value in array where value > 2


The direct _ in the variable definition actually defines a variable, but you don’t want it later, it’s a lazy way of writing



Use the guard statement to solve the above three problems together:

  1. It's about checking what you expect, not what you expect. Again, it is very similar to assert. If the condition is not met, the guard's else statement runs, thereby exiting the function.
  2. If the condition is passed, optional variables are automatically unpacked in the scope where the guard statement is called - in this case the scope inside the fooGuard function. This is an important, and somewhat odd feature, but makes the guard statement very useful.
  3. Early checks for situations you don't expect make the functions you write more readable and maintainable.

func fooGuard(x: Int?)
     guard let x = x where x >  0   else   {
               // When the variable does not meet the condition judgment, execute the following code
               return
     }
     // use x x.description 
}


func fooNonOptionalGood(x: Int) {

  guard x > 0 else {

     return

  }

  // use x

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325542193&siteId=291194637