ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
SwiftUI View က struct ဆိုတော့ immutable ပါ — `var count = 0` ကို View ထဲ ရေးထားရင် value ကို modify လုပ်လို့ မရပါဘူး (compile error)။ `@State private var count = 0` ကို သုံးမှသာ SwiftUI က value ကို View ရဲ့ 'ကျောပေါင်း' မှာ ခွဲသိမ်းထားပေးပြီး, value ပြောင်းတိုင်း View ကို automatic re-render ပေးပါတယ်။ `@Binding` ကတော့ parent ရဲ့ `@State` ကို child View ဆီ 'ချိတ်ဆက်' ပေးတဲ့ property wrapper ပါ — child က value ကို modify လုပ်ရင် parent ရဲ့ state ကိုပါ ချက်ချင်း update ပေးပါတယ် (State Hoisting pattern, Compose နဲ့ ဆင်တူပါတယ်).
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
Counter app တစ်ခုမှာ `@State private var count = 0` ရေးထားပြီး, Button tap ရင် `count += 1` လုပ်ရင် — screen ပေါ်က `Text("\(count)")` က automatic update ဖြစ်ပြီး number တက်သွားတာ တွေ့ရမှာပါ။ `@Binding` ကို သုံးရင် `ToggleSwitch(isOn: $isEnabled)` ဆိုပြီး state ကို parent ကနေ `$` prefix နဲ့ ချိတ်ဆက်ပေးပြီး, `ToggleSwitch` View ကို parent ကွဲပြားစွာ reuse လုပ်နိုင်ပါတယ်.
အတူတူ ကြည့်မယ်
struct Counter: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
.font(.title)
Button("Increment") {
count += 1
}
}
}
}Button ကို tap ရင် 'Count: 0' → 'Count: 1' → 'Count: 2' ဆိုပြီး screen ပေါ် live update ဖြစ်နေတာ တွေ့ရမည်။၅ မိနစ် စမ်းကြည့်
`Counter` View ကို run ကြည့်ပြီး Button ကို ၅ ကြိမ် tap ကြည့်ပါ — count ရဲ့ value live update ဖြစ်နေတာ confirm လုပ်ကြည့်ပါ။ ပြီးရင် `@State` ကို ဖျက်ကြည့်ပြီး ဘယ်လို compile error တွေ့ရလဲ ကြည့်ကြည့်ပါ။
သတိလေးတစ်ချက်
`@State` ကို View ရဲ့ 'local, private' state အတွက်ပဲ သုံးပါ — app-wide state (user login status) အတွက်ကတော့ `@State` မဟုတ်ဘဲ `ObservableObject` (Advanced chapter) ကို သုံးသင့်ပါတယ်။