Skip to Content
Swift📘 Ngôn ngữ SwiftCấu trúc if-else

Cấu trúc rẽ nhánh (if-else) trong Swift

1. If statement cơ bản

let age = 18 if age >= 18 { print("Adult") }

2. If-else

let age = 15 if age >= 18 { print("Adult") } else { print("Minor") }

3. If-else if-else

let score = 85 if score >= 90 { print("A") } else if score >= 80 { print("B") } else if score >= 70 { print("C") } else { print("F") }

4. If với Optional Binding

let name: String? = "Alice" if let unwrappedName = name { print("Hello, \(unwrappedName)") } else { print("No name") }

5. Multiple Conditions

let age = 25 let hasLicense = true // AND if age >= 18 && hasLicense { print("Can drive") } // OR if age < 18 || !hasLicense { print("Cannot drive") }

6. Ternary Operator

let age = 20 let status = age >= 18 ? "Adult" : "Minor" print(status)

7. Guard Statement

func greet(name: String?) { guard let name = name else { print("No name provided") return } print("Hello, \(name)") }

8. If với where clause

let numbers = [1, 2, 3, 4, 5] for number in numbers where number % 2 == 0 { print(number) // 2, 4 }

9. So sánh với Kotlin

SwiftKotlinGhi chú
if condition { }if (condition) { }Giống nhau
if-elseif-elseGiống nhau
guard letKhông cóSwift specific
a ? b : cif (a) b else cTernary

📝 Tóm tắt

  • if - Điều kiện cơ bản
  • if-else if-else - Nhiều nhánh
  • if let - Optional binding
  • guard let - Early return
  • ? : - Ternary operator
  • &&, ||, ! - Logical operators
Last updated on