Browse Questions
- A race condition occurs when two or more threads access shared mutable state simultaneously, producing unpredictable results depending on timing.
- An Optional is a type that can hold either a value or nil.
- Themis is an open-source, cross-platform cryptographic library that packages a few high-level, hard-to-misuse primitives instead of exposing raw ciphers.
- @MainActor is a global actor that ensures code runs on the main thread.
Answer:
@MainActor is a global actor that ensures code runs on the main thread. Use it for UI updates, ViewModels, and any code that must not run off the main thread.
Code Example:
@MainActor
class ProfileViewModel: ObservableObject {
@Published var username: String = ""
@Published var isLoading: Bool = false
func loadProfile() async {
isLoading = true
defer { isLoading = false }
username = try await ProfileService.fetchUsername()
// All assignments happen on main thread automatically
}
}
// Marking just a function (not the whole type)
func updateUI() async {
await MainActor.run {
label.text = "Done"
}
}