In swift syntax the WHERE keyword acts as a where in SQL, that is, additional conditional judgment.
1, in the collection traversal use where, if the condition is true, execute code block, false when not executing code block.
Let array = [0, 1, 2, 3, 4, 5, 6]
//Use switch traversal
Array.foreach {
switch $ {case let
x where x > 3: Where is equivalent to
the judgment condition print ("second half")
default:
print ("Default value")
}
///
Array where value > 2 {
print (value) /Output 3 4 5 6
}
for (index, value) in array.enumerated () where I Ndex > 2 && value > 3 {
print ("Subscript: \ (index), value: \ (value)")
}
Output:
Default value default value default value the second half of the second half paragraph
3
4
5
6 subscript
: 4, Value:
4 subscript: 5, Value: 5 subscript
: 6, Value: 6
2, in the supplementary abnormal Do/catch use
3, where the protocol uses, only the base class implements the current protocol to add extensions. In other words, multiple classes implement the same protocol, which adds extensions to these classes, depending on the class name, respectively.
Protocol Someprotocol {
func somemethod ()
}
class A:someprotocol {let
A = 1
func somemethod () {
print (' Call SomeMethod ')
}
class B {let
a = 2
}
//base Class A inherits the Someprotocol protocol to add an extension
Extension Someprotocol where self:a {
func Showparama () {
print (SELF.A)
}
}
//Inverse, does not conform to the Where condition
extension Someprotocol where self:b {
func Showparama () {
print (SELF.A)
}
} let
obja = a () let
objb = B () //class B is not implemented Someprotocol, all without protocol method
Obja.showparama () //Output 1
Summary: Where keywords can be used in collection traversal, switch/case, protocols, Swift3 where the If let and guard scenes have been replaced by Swift4 commas, such as if Let A=param, a>10 ( The former needs to judge whether it is nil, which is equivalent to the Where condition.