Many people think that Swift in the switch statement and C or C + +, and even OBJC in the same, this is a big fallacy!
Let the cat show you the power of the switch statement pattern match in Swift.
Pattern matching is the use of certain patterns (such as couple) to customize the matching results you need, such as the following 3D space point coordinates:
let point3D:(x:Int,y:Int,z:Int) = (1,2,3)
Let's start with a simple match, just a simple comparison of whether it is equal to or not equal to the specified constant:
switch(point3D){case (0,0,0):print("Origin 3D")case (1000,1000,1000):print("遥远的地方")default:print("other positions")}
The use of switch above is very general, we can see further:
Switch(Point3D) { Case(0,0,0):Print("The Origin") Case(_,0,0):Print("On the x-axis") Case(0,_,0):Print("On the y-axis") Case(0,0,_):Print("on the Z-axis")default:Print("Other positions")}
Note that the above matching pattern of _ indicates that I do not care about the value of the corresponding position, because the first decision has taken into account the origin of the situation, so _ can no longer be 0.
But what if I want to be able to capture the value of the corresponding position in the pattern? It's simple, like a variable declaration, with a let statement:
switch(point3D){case (let x,0,0): print("x is \(x)")}
What if I want to further increase my judgment? Very simple, followed by the WHERE clause:
switch(point3D){case (let x,letwhere y == x: print("y = x")case (_,let y,letwhere y = z*z: print("y = z^2")default:break}
We can freely change the pattern according to the actual demand, and finally give an example:
let mode:(name:String,age:Int) = ("hopy",121)switch(mode){case(let name,letwhere100: print("\(name)\(age) is very young!!!")case(_,letwhere150: print("Ta‘s age is \(age) somewhat old!!!")default: print("hehe...")}
Switch powerful pattern matching in Swift