Mutating Methods क्या हैं
एक mutating method एक special तरह का action है जो एक struct perform कर सकता है जो उसे अपनी properties बदलने की अनुमति देता है।
Syntax
struct TypeName {
var property: Type
mutating func methodName() {
property = newValue
}
}
var instance = TypeName(property: value) // must be var
instance.methodName()
Declaring a Mutating Method
किसी method को mutating चिह्नित करना इसे struct की अपनी stored properties बदलने की अनुमति देता है, जो अन्यथा disallowed है क्योंकि structs value types हैं।
उदाहरण: Declaring a Mutating Method
// Define a struct `Counter`
struct Counter {
// Declare a mutable variable `count`, initialized to `0`
var count = 0
mutating func increment() {
count += 1
}
}
// Declare a mutable variable `counter`, initialized to `Counter()`
var counter = Counter()
counter.increment()
counter.increment()
// Print "Count: \(counter.count)" to the console
print("Count: \(counter.count)")
Login to try C/C++/Java/PHP code in the editor
Mutating Methods Require var Instances
एक mutating method सिर्फ var से declared instance पर call किया जा सकता है, क्योंकि एक let instance पूरी तरह immutable है।
Note:
अगर
lightSwitch var के बजाय let से declared होता, .toggle() call करना compile होने में fail होता।उदाहरण: Mutating Methods Require var Instances
// Define a struct `Switch`
struct Switch {
// Declare a mutable variable `isOn`, initialized to `false`
var isOn = false
mutating func toggle() {
isOn.toggle()
}
}
// Declare a mutable variable `lightSwitch`, initialized to `Switch()`
var lightSwitch = Switch()
lightSwitch.toggle()
// Print "Is on: \(lightSwitch.isOn)" to the console
print("Is on: \(lightSwitch.isOn)")
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. #}
आम गलतियां
- किसी struct method पर
mutatingkeyword भूल जाना जोselfया इसकी किसी property modify करता है, एक compile error का कारण बनते हुए। - एक
letसे declared struct instance पर एकmutatingmethod call करने की कोशिश करना; सिर्फvarinstances mutation allow करते हैं। - गलती से एक class method पर
mutatingजोड़ना; keyword सिर्फ structs और enums के लिए मायने रखता है, classes के लिए नहीं।
चैप्टर सारांश
- Struct methods जो properties modify करते हैं उन्हें
funcसे पहलेmutatingचिह्नित किया जाना चाहिए। - एक
mutatingmethod सिर्फ एकvarमें stored instance पर call किया जा सकता है,letमें नहीं। - Classes को कभी
mutatingकी ज़रूरत नहीं क्योंकि उनके methods हमेशा properties बदल सकते हैं। - एक mutating method यहां तक कि
selfको उसी struct के एक नए instance में पूरी तरह reassign भी कर सकता है।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: