Break và Continue
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”break- Thoát khỏi vòng lặp hoặc switchcontinue- Bỏ qua lần lặp hiện tại
2. break trong vòng lặp
Phần tiêu đề “2. break trong vòng lặp”for i in 1...10 { if i == 5 { break } print(i)}// Output: 1, 2, 3, 43. continue trong vòng lặp
Phần tiêu đề “3. continue trong vòng lặp”for i in 1...5 { if i == 3 { continue } print(i)}// Output: 1, 2, 4, 54. break trong while
Phần tiêu đề “4. break trong while”var count = 0
while true { count += 1 print(count)
if count >= 5 { break }}5. continue trong while
Phần tiêu đề “5. continue trong while”var i = 0
while i < 10 { i += 1 if i % 2 == 0 { continue } print(i)}// Output: 1, 3, 5, 7, 96. break trong switch
Phần tiêu đề “6. break trong switch”let value = 5
switch value {case 1...5: print("Small number") break // Không bắt buộc, không fallthroughcase 6...10: print("Large number")default: break // Empty case cần break}7. Labeled Statements
Phần tiêu đề “7. Labeled Statements”outerLoop: for i in 1...3 { for j in 1...3 { if i == 2 && j == 2 { break outerLoop // Thoát cả 2 vòng } print("\(i) - \(j)") }}8. continue với Label
Phần tiêu đề “8. continue với Label”outerLoop: for i in 1...3 { for j in 1...3 { if j == 2 { continue outerLoop // Tiếp tục vòng ngoài } print("\(i) - \(j)") }}9. Ví dụ thực tế
Phần tiêu đề “9. Ví dụ thực tế”// Tìm phần tửlet items = ["apple", "banana", "cherry", "date"]
for item in items { if item == "cherry" { print("Found: \(item)") break }}// Bỏ qua giá trị nillet values: [Int?] = [1, nil, 2, nil, 3]
for value in values { guard let value = value else { continue } print(value)}// Output: 1, 2, 310. fallthrough trong switch
Phần tiêu đề “10. fallthrough trong switch”let grade = "B"
switch grade {case "A": print("Excellent!") fallthroughcase "B": print("Good job!") fallthroughcase "C": print("You passed")default: print("Try again")}// Output: Good job!, You passed📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”break- thoát vòng lặp/switchcontinue- bỏ qua lần lặp hiện tại- Labeled statements cho nested loops
break outerLoop/continue outerLoopfallthroughđể chuyển case trong switch- Empty switch case cần
break