Bỏ qua để đến nội dung

Switch Statement

let day = 3
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Other day")
}

Lưu ý: Swift không cần break, không có fallthrough mặc định!

let day = 6
switch day {
case 1, 2, 3, 4, 5:
print("Weekday")
case 6, 7:
print("Weekend")
default:
print("Invalid")
}
let score = 85
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
case 50..<70:
print("D")
default:
print("F")
}
let point = (0, 0)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On x-axis")
case (0, _):
print("On y-axis")
default:
print("Somewhere else")
}
let point = (2, 0)
switch point {
case (let x, 0):
print("On x-axis at x = \(x)")
case (0, let y):
print("On y-axis at y = \(y)")
case let (x, y):
print("At (\(x), \(y))")
}
let point = (1, 1)
switch point {
case let (x, y) where x == y:
print("On diagonal")
case let (x, y) where x == -y:
print("On anti-diagonal")
default:
print("Off diagonal")
}
enum Direction {
case north, south, east, west
}
let direction = Direction.north
switch direction {
case .north:
print("Go north")
case .south:
print("Go south")
case .east:
print("Go east")
case .west:
print("Go west")
}
let number = 5
switch number {
case 5:
print("Five")
fallthrough // Tiếp tục case tiếp theo
case 4, 6:
print("Near five")
default:
break
}
Swift Kotlin Ghi chú
switch x { } when (x) { } Tương tự
case 1, 2: 1, 2 -> Multiple values
case 90...100: in 90..100 -> Ranges
default: else -> Default case
Không cần break Không cần break Giống nhau

  • switch - Pattern matching mạnh mẽ
  • Không cần break (không fallthrough)
  • default: bắt buộc (trừ enum exhaustive)
  • Hỗ trợ ranges, tuples, value binding
  • where clause cho điều kiện phức tạp
  • fallthrough để tiếp tục case tiếp theo