Browse Questions
- XCTestExpectation pauses a test until an async condition is fulfilled or a timeout is reached.
- Use a computed property for a cheap, side-effect-free value derived from existing state; use a method for expensive work, side effects, or anything that needs arguments.
- Encapsulation means bundling data with the operations that act on it, and restricting direct access to that data so internal invariants can't be broken from outside.
- @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"
}
}