[Swift] switch statement using tuples

1.First of all


This time, I will introduce a slightly different usage of using tuple values for conditional branching of Switch statements. I think it is an effective way to use it depending on the situation, so please take a look.

2. Use tuples in case


First, if you think of the tuple as a constant and put it on the case label, you can write: However, all tuple types need to be the same, and in this example we assume that the variable day has a tuple that represents a date consisting of months and days. It will be displayed if it matches any of the three holidays listed.

python


switch day {
case (1,1): print("New Year's Day")
case (2,11): print("Foundation Day")
case (5,3): print("Constitution Memorial Day")
default: break
}

You can use the range operator to represent a date in a range. For example, check the following example.

python


switch day {
case (1,1...5): // 1/1 ~ 1/5
    print("new Year holidays")

case (5,3): print("Constitution Memorial Day")

case (4,29), (5,2...6):
    print("Consecutive holidays")

default: break
}

In addition to enumerating values, you can also extract tuple elements and use them for processing. For this purpose, you can write let or var inside the case label to declare constants and variables that are valid only inside the case clause.

python


switch day {
case (5,3): print("Constitution Memorial Day")
case (8, let d): print("8/\(d)Is summer vacation")
default: break
}

In this example, any date in August will be summer vacation. If you don't need to use the variable d, you can also use "_" and write:

python


case (8, _): print("Summer vacation")

You can also use tuples with keywords in switch statements, but an error will occur if the values and the keywords used in the case label do not match. In Swift, the general process of checking the structure and value match, such as the correspondence between tuple and case labels, is called ** pattern matching **.

3. Use where clause in switch statement


You can also condition the tuple elements with a switch statement. Here, we use the function dayOfWeek that calculates the day of the week from the date. This function returns the day of the week as an integer value, such as 0 for Sunday, 1 for Monday, and so on. Note that the variable year has the year. When adding a condition to the case label, write the reserved word where and the condition between the label and ":". Check the example below.

python


switch day {
case (1, let d) where d >= 8 && d <= 14 && dayOfWeek(year,1,d) == 1:
    print("Coming of age day")

case (8, _): print("Summer vacation")

case (let m, let d) where dayOfWeek(year,m,d) == 0:
    print("\(m)/\(d)Is sunday")

default: break
}

The condition here is that the second Monday of January is Coming-of-Age Day. Similarly, it is displayed on Sundays at any time of the year. If you want to assign all the elements of a tuple to a constant like this case label, you can specify a let for each element, but you can also write only one let before the tuple.

python


case let (m, d) where dayOfWeek(year,m,d) == 0:
    print("\(m)/\(d)Is sunday")

The method of specifying conditions using let, var, and where in the case label can be used not only for tuples but also for ordinary integers.

Labels that use constants and variables have restrictions when they are arranged separately, separated by ",". This is because constants and variables may have no value, depending on which label's condition was met. For example, you cannot do the following:

python


switch t {
case (1, let y), (2, 2):
    print("\(y)")

case (2, _):
    fallthrough

case (let z, 2):
    print("\(z)")
default: break
}

You cannot use the fallthrough statement to transition from the option immediately above to the case clause that uses constants or variables in the case label.

When labels are listed separated by ",", the condition that they may contain constants or variables is that all labels contain constants or variables of the same name and type. In other words, in any case, the value of a constant or variable must be fixed. Please be careful only on that point.

4. Use optional type in switch statement


Even if the expression you want to separate in the switch statement contains an optional type value, you can write it in the case label. As an example, consider a tuple type consisting of a name and an age. However, since the age may be unknown, it is an optional type.

python


typealias People = (String, Int?)

To handle such types in Switch statements, use the "?" Symbol in the case pattern.

python


switch m {
case let (name, age?) where age >= 18:
    print("\(name),License can be obtained")

case let (name, (15...18)?):
    print("\(name),High school student")

case (let name, nil):
    print("\(name),Age unknown")

default: break
}

In this way, if you add "?" To the corresponding constant or variable, it will match when the optional type has a value other than nil, and you can refer to the value in the where clause or execution after that without using the disclosure operator. I will. Also, if you describe nil, it will match if the optional type has a value of nil. Enclose the pattern indicating the range in ().

The "?" To indicate that it is optional can be used for other patterns such as tuples. For example, if the Pepole? Type variable ops is used in a switch statement, the case can be described as follows.

python


switch ops {            //ops is People?Type
case let (name, 18?)? : //The disclosed result is(String, 18)Then match

5. Conclusion


This time I wrote about how to use the switch statement using tuples. Next time, I'm thinking of writing an article about ** enums **, so please take a look if you like. Thank you to everyone who has seen this far.

Recommended Posts

[Swift] switch statement using tuples
switch statement
Java switch statement
Switch statement range specification
Studying Java-Part 11-switch statement
Swift conditional branch statement summary
[Swift] Try using Collection View
[Swift] Share data using AppDelegate
Let's understand the switch statement!
[Swift] Asynchronous processing using PromiseKit
[Swift] Implement UITableView using xib
[Java] Branch enum with switch statement
[Swift] "for-in statement" about iterative processing
[Java] Really scary switch statement story
I met a great switch statement