Switch powerful pattern matching in Swift

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.