Mutating Keyword in Swift

emre gürses
1 min readJan 31, 2023

One of the most populer question in iOS interview, what is the mutating keyword?

Let’s look at the this keyword meaning.

The mutating keyword in Swift is used before the declaration of a method or property in a struct or an enumeration(not in the class) to indicate that the method or property can modify the underlying struct or enumeration instance.

In other words, mutating allows you to modify the values of the struct or enumeration's properties within the method or property. If a struct or enumeration method or property doesn't need to modify the instance, it can be declared without the mutating keyword.

Here’s an example of a mutating method in a struct:

struct TransactionOrder {
var indexOrder: Int

mutating func increment() {
indexOrder += 1
}
}

if you want to change de value of the indexOrder, you should declare mutating keyword before the increment() func in Swift.

In this example, the increment method increments the value of the value property. The mutating keyword allows the method to modify the value property of the struct instance, even though TransactionOrder is a value type (as opposed to a reference type).

NOTE :mutating keyword uses in struct or an enumeration not in the class

--

--

emre gürses

Denizbank — Intertech, Mobil Uygulama Geliştiricisi(iOS)