Mutating Methods
Kyunke struct ek value type hai, struct par ek instance method default mein self ko read-only treat karta hai — struct ke andar define kiya gaya method bhi apni ek property tab tak change nahi kar sakta jab tak usay explicitly mutating mark na kiya jaye. Ye waqai ek Swift-specific rule hai: is site ki koi bhi class-based language ko iski zaroorat nahi, kyunke wahan har class pehle se ek reference type hai jahan methods apni fields azadi se change kar sakte hain.
Real Compiler Error Kaisa Dikhta Hai
Ek struct method jo property change karne ki koshish karta hai, us se mutating chhor dena warning nahi hai — ye ek compile error hai. Ye waqai wohi hai jo compiler report karta hai — ek real run se capture kiya gaya, plausible dikhne ke liye likha hua nahi:
struct Counter {
var count: Int = 0
func increment() {
count += 1
}
}
var c = Counter()
c.increment()
print(c.count)Main.swift:5:15: error: left side of mutating operator isn't mutable: 'self' is immutable
count += 1
~~~~~ ^
Main.swift:4:5: note: mark method 'mutating' to make 'self' mutable
func increment() {
^
mutating
func se pehle mutating add karna isay faoran fix kar deta hai — ye compiler ko batata hai ke ye specific method self ki properties replace karne ki ijazat rakhta hai, aur isay call karne ke liye ek var instance chahiye (ek let Counter isay bilkul call nahi kar pata).
struct Counter {
var count: Int = 0
mutating func increment() {
count += 1
}
}
var c = Counter()
c.increment()
c.increment()
print(c.count)2
Aage: properties — computed properties aur property observers, jo read ya write par khud ba khud code run karte hain.
Practice exercise
Ek struct Counter naam ka define karein jis mein var count: Int = 0 ho aur ek mutating method increment() ho jo count mein 1 add kare. var c = Counter() banayein, c.increment() teen bar call karein, phir c.count print karein.