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
| Swift | Kotlin | Ghi chú |
|---|---|---|
if condition { } | if (condition) { } | Giống nhau |
if-else | if-else | Giống nhau |
guard let | Không có | Swift specific |
a ? b : c | if (a) b else c | Ternary |
📝 Tóm tắt
if- Điều kiện cơ bảnif-else if-else- Nhiều nhánhif let- Optional bindingguard let- Early return? :- Ternary operator&&,||,!- Logical operators
Last updated on
Swift