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

Cấu trúc if-else

let age = 18
if age >= 18 {
print("Adult")
}
let age = 15
if age >= 18 {
print("Adult")
} else {
print("Minor")
}
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else if score >= 70 {
print("C")
} else {
print("F")
}
let name: String? = "Alice"
if let unwrappedName = name {
print("Hello, \(unwrappedName)")
} else {
print("No name")
}
let age = 25
let hasLicense = true
// AND
if age >= 18 && hasLicense {
print("Can drive")
}
// OR
if age < 18 || !hasLicense {
print("Cannot drive")
}
let age = 20
let status = age >= 18 ? "Adult" : "Minor"
print(status)
func greet(name: String?) {
guard let name = name else {
print("No name provided")
return
}
print("Hello, \(name)")
}
let numbers = [1, 2, 3, 4, 5]
for number in numbers where number % 2 == 0 {
print(number) // 2, 4
}
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

  • 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