Skip to Content

Guard Statement trong Swift

1. Giới thiệu

guard là cách Swift kiểm tra điều kiện và thoát sớm nếu điều kiện không thỏa mãn.

2. Cú pháp cơ bản

func checkAge(_ age: Int) { guard age >= 0 else { print("Invalid age") return } print("Age is valid: \(age)") }

3. Guard với Optional Unwrapping

func greet(_ name: String?) { guard let name = name else { print("No name provided") return } // name bây giờ là non-optional print("Hello, \(name)!") } greet("Alice") // Hello, Alice! greet(nil) // No name provided

4. Guard vs If-let

// Với if-let - phải lồng code func processWithIf(value: Int?) { if let value = value { if value > 0 { print("Processing: \(value)") } } } // Với guard - code flat hơn func processWithGuard(value: Int?) { guard let value = value else { return } guard value > 0 else { return } print("Processing: \(value)") }

5. Nhiều điều kiện

func validateUser(name: String?, age: Int?, email: String?) { guard let name = name, let age = age, let email = email else { print("Missing required fields") return } guard !name.isEmpty, age >= 18, email.contains("@") else { print("Invalid data") return } print("Valid user: \(name), \(age), \(email)") }

6. Guard với where

func processNumber(_ input: String?) { guard let input = input, let number = Int(input), number > 0 else { print("Invalid input") return } print("Number: \(number)") }

7. Guard trong loops

let data = ["1", "two", "3", "four", "5"] for item in data { guard let number = Int(item) else { print("Skipping: \(item)") continue } print("Number: \(number)") }

8. Guard với throw

enum ValidationError: Error { case emptyName case invalidAge } func validatePerson(name: String?, age: Int?) throws -> (String, Int) { guard let name = name, !name.isEmpty else { throw ValidationError.emptyName } guard let age = age, age >= 0 else { throw ValidationError.invalidAge } return (name, age) }

9. Early Exit Pattern

func processPayment(amount: Double?, cardNumber: String?, cvv: String?) -> Bool { guard let amount = amount, amount > 0 else { print("Invalid amount") return false } guard let cardNumber = cardNumber, cardNumber.count == 16 else { print("Invalid card number") return false } guard let cvv = cvv, cvv.count == 3 else { print("Invalid CVV") return false } print("Processing payment: \(amount)") return true }

10. Best Practices

// ✅ Dùng guard cho early exit func good(value: Int?) { guard let value = value, value > 0 else { return } // Happy path code here } // ❌ Không dùng guard khi cần else branch phức tạp func notIdeal(value: Int?) { guard let value = value else { // Nhiều logic ở đây -> dùng if-let return } }

📝 Tóm tắt

  • guard kiểm tra điều kiện và thoát sớm
  • Phải có return, throw, continue, hoặc break
  • Unwrap optionals với scope ngoài guard
  • Giữ code flat, tránh lồng sâu
  • Tốt cho early validation pattern
Last updated on