Skip to content

Commit 17a4b61

Browse files
committed
Examples 14-18
1 parent fa20808 commit 17a4b61

File tree

5 files changed

+375
-144
lines changed

5 files changed

+375
-144
lines changed

contents/[14]switch-case/index.md

Lines changed: 156 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,176 @@ order: 14
55
---
66

77

8-
foo
8+
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:
99

1010
```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+
```
1424

15-
z = x + y // addition
16-
print(z) // => 10
25+
If the cases are exhaustive, the default case is optional:
1726

18-
z = x - y // subtraction
19-
print(z) // => 0
27+
```swift
28+
let isCompleted = true
29+
30+
switch isCompleted {
31+
case true:
32+
print("Task is ready.")
33+
case false:
34+
print("Task is not completed.")
35+
}
36+
```
2037

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:
2339

24-
z = x / y // division
25-
print(z) // => 1
40+
```swift
41+
let someCharacter: Character = "E"
42+
43+
switch someCharacter.lowercased() {
44+
case "a", "e", "i", "o", "u":
45+
print("\(someCharacter) is a vowel")
46+
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
47+
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
48+
print("\(someCharacter) is a consonant")
49+
default:
50+
print("\(someCharacter) isn't a vowel or a consonant")
51+
}
52+
```
2653

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:
2755

28-
var x = 10
2956

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+
```
3271

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:
3573

36-
x *= 2 // multiplication
37-
print(x) // => 20
74+
```swift
75+
print("Loading website...")
3876

39-
x /= 2 // division
40-
print(x) // => 10
77+
let statusCode = 404
78+
79+
switch statusCode {
80+
case 200:
81+
    break
82+
case 404:
83+
    print("Not found")
84+
default:
85+
    print("Unknown status code")
86+
}
87+
88+
print("Done.")
4189
```
4290

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:
4492

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+
case 90...100:
116+
print("Excellent! You got an A.")
117+
case 80...89:
118+
print("Good job! You got a B.")
119+
case 70...79:
120+
print("Keep it up! You got a C.")
121+
case 60...69:
122+
print("You passed with a D.")
123+
default:
124+
print("You need to improve. You got an F.")
125+
}
47126
```
48127

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+
case let (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.
179+
180+

contents/[15]while/index.md

Lines changed: 34 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,46 +4,48 @@ description: ""
44
order: 15
55
---
66

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.
78

8-
foo
9+
Let's look at a basic example:
910

1011
```swift
11-
let x = 5
12-
let y = 5
13-
var z = 0
12+
var counter = 1
1413

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+
```
3519

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:
3821

39-
x /= 2 // division
40-
print(x) // => 10
22+
```swift
23+
var counter = 1
24+
25+
while true {
26+
print("Count is \(counter)")
27+
if counter == 5 {
28+
break
29+
}
30+
counter += 1
31+
}
4132
```
4233

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:
4435

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+
}
4748
```
4849

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`.
51+

contents/[16]repeat-while/index.md

Lines changed: 39 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,54 @@ order: 16
55
---
66

77

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.
99

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:
2611

2712

28-
var x = 10
13+
```swift
14+
var counter = 1
2915

30-
x += 2 // addition
31-
print(x) // => 12
16+
repeat {
17+
print("Count is \(counter)")
18+
counter += 1
19+
}
20+
while counter <= 5
21+
```
3222

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:
3524

36-
x *= 2 // multiplication
37-
print(x) // => 20
3825

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
4139
```
4240

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:
4442

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
4756
```
4857

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

Comments
 (0)