Cấu trúc if-else
1. If statement cơ bản
Phần tiêu đề “1. If statement cơ bản”let age = 18
if age >= 18 { print("Adult")}2. If-else
Phần tiêu đề “2. If-else”let age = 15
if age >= 18 { print("Adult")} else { print("Minor")}3. If-else if-else
Phần tiêu đề “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
Phần tiêu đề “4. If với Optional Binding”let name: String? = "Alice"
if let unwrappedName = name { print("Hello, \(unwrappedName)")} else { print("No name")}5. Multiple Conditions
Phần tiêu đề “5. Multiple Conditions”let age = 25let hasLicense = true
// ANDif age >= 18 && hasLicense { print("Can drive")}
// ORif age < 18 || !hasLicense { print("Cannot drive")}6. Ternary Operator
Phần tiêu đề “6. Ternary Operator”let age = 20let status = age >= 18 ? "Adult" : "Minor"print(status)7. Guard Statement
Phần tiêu đề “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
Phần tiêu đề “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
Phần tiêu đề “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
Phần tiêu đề “📝 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