AnyCompiler

Mutating Methods

Kyunki 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 use explicitly mutating mark na kiya jaaye. Ye genuinely ek Swift-specific rule hai: is site ki koi bhi class-based language ko iski zaroorat nahi, kyunki wahan har class already ek reference type hai jahan methods apni fields freely change kar sakte hain.

Real Compiler Error Kaisa Dikhta Hai

Ek struct method jo property change karne ki koshish karta hai, usse mutating chhod dena warning nahi hai — ye ek compile error hai. Ye genuinely wahi 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)
Output
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 isse immediately fix kar deta hai — ye compiler ko batata hai ki ye specific method self ki properties replace karne ki permission rakhta hai, aur isse call karne ke liye ek var instance chahiye (ek let Counter use 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)
Output
2

Aage: properties — computed properties aur property observers, jo read ya write par automatically code run karte hain.

Practice exercise

Ek struct Counter naam ka define karo jisme var count: Int = 0 ho aur ek mutating method increment() ho jo count mein 1 add kare. var c = Counter() banao, c.increment() teen baar call karo, phir c.count print karo.