MainActor क्या है
MainActor एक special label है जिसका मतलब है "इस code को main thread पर चलना चाहिए," जो screen को छूने वाली किसी भी चीज़ के लिए महत्वपूर्ण है।
Syntax
@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
@MainActor
func updateStatus(_ message: String) {
print("Status updated on main actor: \(message)")
}
await updateStatus("Ready")
Login to try C/C++/Java/PHP code in the editor
A MainActor-Isolated Property
एक पूरा type या एक specific property main actor से isolated हो सकता है, यह सुनिश्चित करते हुए कि इसमें सभी access properly main thread से synchronized है।
उदाहरण: A MainActor-Isolated Property
@MainActor
class ViewState {
var title: String = "Loading"
}
let state = await ViewState()
await MainActor.run {
state.title = "Loaded"
}
let title = await state.title
print(title)
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह भूल जाना कि एक असली app में UI-related code को main thread पर चलना चाहिए;
@MainActorइसे compile time पर enforce करता है। - भारी computational work पर
@MainActorapply करना, जो इसे अनावश्यक रूप से एक background context के बजाय main thread पर मजबूर करता है। - यह मान लेना कि
@MainActorcode किसी भी context से बिनाawaitsynchronously चलता है; इसे एक non-main-actor context से call करना अब भी hop को await करने की मांग करता है।
चैप्टर सारांश
@MainActorकिसी function, property, या type को main thread पर चलना required के रूप में चिह्नित करता है।- यह किसी भी code के लिए ज़रूरी है जिसे careful ordered fashion में चलना चाहिए, जैसे असली apps में UI updates।
- Main actor के context से बाहर से
@MainActorcode call करने के लिएawaitचाहिए। @MainActormain queue को manually काम dispatch करने का Swift का structured replacement है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: