You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The switch statement executes the code for the first case that matches the value, just like the if statement does when a condition is true. Swift's switch statement is exhaustive—every possible value must be handled, either by listing each one explicitly or by including a default case:
9
9
10
10
```swift
11
-
let x =5
12
-
let y =5
13
-
var z =0
11
+
let day ="Monday"
12
+
13
+
switch day {
14
+
case"Monday":
15
+
print("Start the work week.")
16
+
case"Saturday":
17
+
print("Relax, it's the weekend!")
18
+
case"Sunday":
19
+
print("Prepare for the week ahead.")
20
+
default:
21
+
print("It's a regular weekday.")
22
+
}
23
+
```
14
24
15
-
z = x + y // addition
16
-
print(z) // => 10
25
+
If the cases are exhaustive, the default case is optional:
17
26
18
-
z = x - y // subtraction
19
-
print(z) // => 0
27
+
```swift
28
+
let isCompleted =true
29
+
30
+
switch isCompleted {
31
+
casetrue:
32
+
print("Task is ready.")
33
+
casefalse:
34
+
print("Task is not completed.")
35
+
}
36
+
```
20
37
21
-
z = x * y // multiplication
22
-
print(z) // => 25
38
+
Sometimes, different values should be handled in the same way. You can group multiple values into a single case by listing them and separating each one with a comma:
print("\(someCharacter) isn't a vowel or a consonant")
51
+
}
52
+
```
26
53
54
+
It is also possible to use a switch-case to conditionally set values, using the assignment operator, just like you have seen it with if-else. Extract and use values from the matched data like here:
27
55
28
-
var x =10
29
56
30
-
x +=2// addition
31
-
print(x) // => 12
57
+
```swift
58
+
let anotherCharacter: Character="a"
59
+
60
+
let message =switch anotherCharacter {
61
+
case"a":
62
+
"The first letter of the Latin alphabet"
63
+
case"z":
64
+
"The last letter of the Latin alphabet"
65
+
default:
66
+
"Some other character"
67
+
}
68
+
69
+
print(message)
70
+
```
32
71
33
-
x -=2// subtraction
34
-
print(x) // => 10
72
+
Break can be used to match and ignore one or more cases in a switch statement. It causes the switch statement to end its execution immediately:
35
73
36
-
x *=2// multiplication
37
-
print(x) // => 20
74
+
```swift
75
+
print("Loading website...")
38
76
39
-
x /=2// division
40
-
print(x) // => 10
77
+
let statusCode =404
78
+
79
+
switch statusCode {
80
+
case200:
81
+
break
82
+
case404:
83
+
print("Not found")
84
+
default:
85
+
print("Unknown status code")
86
+
}
87
+
88
+
print("Done.")
41
89
```
42
90
43
-
bar
91
+
The **fallthrough** keyword, on the other hand, tells Swift to continue execution to the next case, even if there was already a match:
44
92
45
-
```sh
46
-
swift main.swift
93
+
```swift
94
+
let weather ="warm"
95
+
96
+
switch weather {
97
+
case"cold":
98
+
print("It's a cold day.")
99
+
case"warm":
100
+
print("It's a warm day.")
101
+
fallthrough
102
+
case"sunny":
103
+
print("It must be sunny too.")
104
+
default:
105
+
break
106
+
}
107
+
```
108
+
109
+
Interval matching in a switch statement works much like checking ranges using an if statement, but the syntax is different and usually easier to read:
110
+
111
+
```swift
112
+
let grade =95
113
+
114
+
switch grade {
115
+
case90...100:
116
+
print("Excellent! You got an A.")
117
+
case80...89:
118
+
print("Good job! You got a B.")
119
+
case70...79:
120
+
print("Keep it up! You got a C.")
121
+
case60...69:
122
+
print("You passed with a D.")
123
+
default:
124
+
print("You need to improve. You got an F.")
125
+
}
47
126
```
48
127
49
-
baz
128
+
Switch statements in Swift support pattern matching, which means you can match values not only with intervals, but also with tuples, value bindings, and even more complex patterns:
129
+
130
+
```swift
131
+
let first: Bool=true
132
+
let second: Bool=false
133
+
134
+
switch (first, second) {
135
+
case (true, true):
136
+
print("Both true")
137
+
case (true, false):
138
+
print("First true")
139
+
case (false, true):
140
+
print("Second true")
141
+
case (false, false):
142
+
print("Both false")
143
+
}
144
+
```
145
+
146
+
You can also ignore values (match any value) by using an underscore character:
147
+
148
+
```swift
149
+
let point = (0, 0)
150
+
151
+
switch point {
152
+
case (0, 0):
153
+
print("Origin")
154
+
case (_, 0):
155
+
print("On the X-axis")
156
+
case (0, _):
157
+
print("On the Y-axis")
158
+
default:
159
+
print("Somewhere else")
160
+
}
161
+
```
162
+
163
+
You can capture the values that match a pattern using value binding, allowing you to use those values directly within the case block:
164
+
165
+
```swift
166
+
let point = (2, 3)
167
+
168
+
switch point {
169
+
case (let x, 0):
170
+
print("On the X-axis at x = \(x)")
171
+
case (0, let y):
172
+
print("On the Y-axis at y = \(y)")
173
+
caselet (x, y):
174
+
print("At some other point: (\(x), \(y))")
175
+
}
176
+
```
177
+
178
+
This approach gives you direct access to the data while also matching its structure. It's a powerful feature of Swift's switch statement.
Copy file name to clipboardExpand all lines: contents/[15]while/index.md
+34-32Lines changed: 34 additions & 32 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,46 +4,48 @@ description: ""
4
4
order: 15
5
5
---
6
6
7
+
Unlike some other loop types, a while loop is especially useful when you don't know in advance how many times the code should run, but you do have a condition that controls when to stop. As long as that condition holds true, the loop keeps working.
7
8
8
-
foo
9
+
Let's look at a basic example:
9
10
10
11
```swift
11
-
let x =5
12
-
let y =5
13
-
var z =0
12
+
var counter =1
14
13
15
-
z = x + y // addition
16
-
print(z) // => 10
17
-
18
-
z = x - y // subtraction
19
-
print(z) // => 0
20
-
21
-
z = x * y // multiplication
22
-
print(z) // => 25
23
-
24
-
z = x / y // division
25
-
print(z) // => 1
26
-
27
-
28
-
var x =10
29
-
30
-
x +=2// addition
31
-
print(x) // => 12
32
-
33
-
x -=2// subtraction
34
-
print(x) // => 10
14
+
while counter <=5 {
15
+
print("Count is \(counter)")
16
+
counter +=1
17
+
}
18
+
```
35
19
36
-
x *=2// multiplication
37
-
print(x) // => 20
20
+
Let's see how you can use the break statement to avoid unwanted infinite loops. We will modify the previous example by adding a line of code that allows the loop to exit once a certain condition is met:
38
21
39
-
x /=2// division
40
-
print(x) // => 10
22
+
```swift
23
+
var counter =1
24
+
25
+
whiletrue {
26
+
print("Count is \(counter)")
27
+
if counter ==5 {
28
+
break
29
+
}
30
+
counter +=1
31
+
}
41
32
```
42
33
43
-
bar
34
+
In Swift, the **continue** keyword is used inside loops to skip the current iteration and move directly to the next one. This is helpful when you want to _ignore certain values_ and still continue the loop:
44
35
45
-
```sh
46
-
swift main.swift
36
+
```swift
37
+
var number =0
38
+
39
+
while number <10 {
40
+
number +=1
41
+
42
+
if number %2==0 {
43
+
continue// Skip even numbers
44
+
}
45
+
46
+
print("Odd number: \(number)")
47
+
}
47
48
```
48
49
49
-
baz
50
+
In this example, we start with a variable called `number` set to `0`. As long as `number` is less than `10`, we increase its value by `1` in each loop iteration. If `number` can be divided by `2` with no remainder, it means the number is even, so the program uses the `continue` statement to skip printing and immediately returns to the beginning of the loop. This process repeats until `number` reaches `10`.
Copy file name to clipboardExpand all lines: contents/[16]repeat-while/index.md
+39-30Lines changed: 39 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,45 +5,54 @@ order: 16
5
5
---
6
6
7
7
8
-
foo
8
+
The **repeat-while** loop is very similar to the while loop, but it always runs at least once. Even if the condition is false at the start, the body of the loop is executed first, and then the condition is evaluated.
9
9
10
-
```swift
11
-
let x =5
12
-
let y =5
13
-
var z =0
14
-
15
-
z = x + y // addition
16
-
print(z) // => 10
17
-
18
-
z = x - y // subtraction
19
-
print(z) // => 0
20
-
21
-
z = x * y // multiplication
22
-
print(z) // => 25
23
-
24
-
z = x / y // division
25
-
print(z) // => 1
10
+
Here's the basic counter example using a repeat-while loop:
26
11
27
12
28
-
var x =10
13
+
```swift
14
+
var counter =1
29
15
30
-
x +=2// addition
31
-
print(x) // => 12
16
+
repeat {
17
+
print("Count is \(counter)")
18
+
counter +=1
19
+
}
20
+
while counter <=5
21
+
```
32
22
33
-
x -=2// subtraction
34
-
print(x) // => 10
23
+
The break keyword can be used inside a repeat-while loop to exit the loop early—before the condition becomes false:
35
24
36
-
x *=2// multiplication
37
-
print(x) // => 20
38
25
39
-
x /=2// division
40
-
print(x) // => 10
26
+
```swift
27
+
var counter =0
28
+
29
+
repeat {
30
+
print("Counter: \(counter)")
31
+
counter +=1
32
+
33
+
if counter ==5 {
34
+
print("Breaking the loop at counter = 5")
35
+
break
36
+
}
37
+
}
38
+
while counter <10
41
39
```
42
40
43
-
bar
41
+
The continue statement also works with repeat-while loops in the same way it does with regular while loops. It allows you to skip the rest of the current iteration and move directly to the next cycle of the loop:
44
42
45
-
```sh
46
-
swift main.swift
43
+
```swift
44
+
var number =0
45
+
46
+
repeat {
47
+
number +=1
48
+
49
+
if number %2==0 {
50
+
continue// Skip even numbers
51
+
}
52
+
53
+
print("Odd number: \(number)")
54
+
}
55
+
while number <10
47
56
```
48
57
49
-
baz
58
+
The snippet above is the repeat-while version of the "print odd numbers" example that we saw in the previous example.
0 commit comments