Component - MainActor for UI updates
This component shows how to use MainActor in Swift to ensure UI updates happen on the main thread. It helps keep the app responsive and prevents UI glitches by running UI code safely on the main thread.
This component shows how to use MainActor in Swift to ensure UI updates happen on the main thread. It helps keep the app responsive and prevents UI glitches by running UI code safely on the main thread.
ViewController
└── View
├── Label
└── Button@MainActor in Swift UI code?@MainActor
class ViewModel {
var count = 0
func increment() {
count += 1
}
}
let vm = ViewModel()
Task {
await vm.increment()
print(vm.count)
}
What will be printed?func updateLabel() {
label.text = "Hello"
}
When called from a background thread, the app crashes. How can you fix it using MainActor?@MainActor and async/await to update the UI?Pass the test and this pattern moves unknown