ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Optional (`?`, `if let`, `guard let`) ကို iOS development မှာ constant သုံးရပါတယ် — API response, user input တွေမှာ 'value ရှိချင်မှ ရှိမယ်' ဆိုတဲ့ scenario တွေမှာ crash ကို ကာကွယ်ဖို့ အရေးကြီးပါတယ်။ Closure (`{ ... }`) ကို button action, list transformation တွေမှာ တွေ့ရမှာပါ။ Struct (`struct Todo { var title: String; var isDone: Bool = false }`) ကို app ရဲ့ data model (todo item, user profile) ကို ကိုယ်စားပြုဖို့ တွေ့ရမှာပါ — SwiftUI View တွေကလည်း struct ပါပဲ (class မဟုတ်ပါ) — ဒါက performance အတွက် intentional design ပါ.
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
`var name: String? = nil` လို့ ရေးထားရင် 'name' က nil ဖြစ်နိုင်တယ် ဆိုတာ compiler ကို ပြောတာပါ — `guard let unwrappedName = name else { return }` ရေးရင် name nil ဖြစ်ရင် function ကို early-return လုပ်ပြီး crash ကို ကာကွယ်ပါတယ်။ Button action ကို `Button("Save") { print("saved") }` လို့ trailing closure syntax နဲ့ ရေးတာကို SwiftUI (နောက် lesson) မှာ ထပ်ခါထပ်ခါ တွေ့ရမှာပါ.
အတူတူ ကြည့်မယ်
// Optional safety
var name: String? = nil
func greet() {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)!")
}
// Struct — will represent our UI data later
struct TodoItem: Identifiable {
let id = UUID()
var title: String
var isDone: Bool = false
}$ greet()
No name provided၅ မိနစ် စမ်းကြည့်
`TodoItem` struct ကို ကိုယ်တိုင် ရေးကြည့်ပြီး, instance ၂-၃ ခု create ကာ Xcode Playground ထဲမှာ `print` output ကို ကြည့်ကြည့်ပါ။
သတိလေးတစ်ချက်
`!` ကို 'nil ဖြစ်နိုင်တဲ့အရာကို nil မဟုတ်ဘူးလို့ force ပြောတာ' ဆိုတာ သတိထားပါ — အမှန်တကယ် nil ဖြစ်နေရင် app crash ချက်ချင်း ဖြစ်ပါလိမ့်မယ်။