0
0
Swiftprogramming~5 mins

Mutating methods for value types in Swift

Choose your learning style9 modes available
Introduction

Mutating methods let you change the data inside value types like structs. Without them, value types cannot change their own properties.

When you want a struct to update its own properties inside a method.
When you need to change a value type's data after it is created.
When you want to keep your data safe but still allow controlled changes.
When you want to write clear code that shows which methods change data.
Syntax
Swift
struct MyStruct {
    var value: Int

    mutating func changeValue(newValue: Int) {
        value = newValue
    }
}

The mutating keyword must be before the function name.

Only value types like struct and enum need mutating for methods that change properties.

Examples
This method increases the count by 1 inside the struct.
Swift
struct Counter {
    var count = 0

    mutating func increment() {
        count += 1
    }
}
This method moves the point by changing its x and y values.
Swift
struct Point {
    var x = 0, y = 0

    mutating func moveBy(dx: Int, dy: Int) {
        x += dx
        y += dy
    }
}
This method switches the enum value between on and off.
Swift
enum LightSwitch {
    case on, off

    mutating func toggle() {
        switch self {
        case .on: self = .off
        case .off: self = .on
        }
    }
}
Sample Program

This program shows a bank account struct that can add or remove money using mutating methods. It prints the balance after each change and warns if there is not enough money.

Swift
struct BankAccount {
    var balance: Double

    mutating func deposit(amount: Double) {
        balance += amount
    }

    mutating func withdraw(amount: Double) {
        if amount <= balance {
            balance -= amount
        } else {
            print("Insufficient funds")
        }
    }
}

var myAccount = BankAccount(balance: 100.0)
myAccount.deposit(amount: 50.0)
print("Balance after deposit: \(myAccount.balance)")
myAccount.withdraw(amount: 30.0)
print("Balance after withdrawal: \(myAccount.balance)")
myAccount.withdraw(amount: 150.0)
OutputSuccess
Important Notes

You cannot call mutating methods on constants (let) because they cannot change.

Mutating methods can also assign a new value to self to replace the whole instance.

Summary

Use mutating before methods that change properties in structs or enums.

Mutating methods let value types update their own data safely.

They cannot be used on constants because constants cannot change.