Break và Continue trong Swift
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
for i in 1...10 {
if i == 5 {
break
}
print(i)
}
// Output: 1, 2, 3, 43. 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
var count = 0
while true {
count += 1
print(count)
if count >= 5 {
break
}
}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
let value = 5
switch value {
case 1...5:
print("Small number")
break // Không bắt buộc, không fallthrough
case 6...10:
print("Large number")
default:
break // Empty case cần break
}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
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ế
// 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ị nil
let 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
let grade = "B"
switch grade {
case "A":
print("Excellent!")
fallthrough
case "B":
print("Good job!")
fallthrough
case "C":
print("You passed")
default:
print("Try again")
}
// Output: Good job!, You passed📝 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
Last updated on
Swift