← Back to Swift Course | Chapter 13: Concurrency | Lesson 4 of 6

MainActor क्या है

MainActor एक special label है जिसका मतलब है "इस code को main thread पर चलना चाहिए," जो screen को छूने वाली किसी भी चीज़ के लिए महत्वपूर्ण है।
Syntax
swift
@MainActor
func functionName() {
    // runs on the main thread
}

@MainActor
class TypeName {
    var property: Type
}

Marking a Function with @MainActor

@MainActor से annotated एक function का main actor के thread पर चलना guaranteed है, जिसे दूसरे contexts से callers को इसमें switch करने के लिए await करना चाहिए।

उदाहरण: Marking a Function with @MainActor

markup
@MainActor
func updateStatus(_ message: String) {
    print("Status updated on main actor: \(message)")
}

await updateStatus("Ready")

A MainActor-Isolated Property

एक पूरा type या एक specific property main actor से isolated हो सकता है, यह सुनिश्चित करते हुए कि इसमें सभी access properly main thread से synchronized है।

उदाहरण: A MainActor-Isolated Property

markup
@MainActor
class ViewState {
    var title: String = "Loading"
}

let state = await ViewState()
await MainActor.run {
    state.title = "Loaded"
}
let title = await state.title
print(title)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि एक असली app में UI-related code को main thread पर चलना चाहिए; @MainActor इसे compile time पर enforce करता है।
  2. भारी computational work पर @MainActor apply करना, जो इसे अनावश्यक रूप से एक background context के बजाय main thread पर मजबूर करता है।
  3. यह मान लेना कि @MainActor code किसी भी context से बिना await synchronously चलता है; इसे एक non-main-actor context से call करना अब भी hop को await करने की मांग करता है।
चैप्टर सारांश
  • @MainActor किसी function, property, या type को main thread पर चलना required के रूप में चिह्नित करता है।
  • यह किसी भी code के लिए ज़रूरी है जिसे careful ordered fashion में चलना चाहिए, जैसे असली apps में UI updates।
  • Main actor के context से बाहर से @MainActor code call करने के लिए await चाहिए।
  • @MainActor main queue को manually काम dispatch करने का Swift का structured replacement है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.