Let's see the example:

// Example Swift code
struct Point {
    var x: Int
    var y: Int
}

struct Size {
    var width: Int
    var height: Int
}

struct Rectangle {
    var origin: Point
    var size: Size
    mutating func moveBy(x: Int, y: Int) {
        origin.x += x
        origin.y += y
    }
}

var rect = Rectangle(origin: Point(x: 0, y: 0), size: Size(width: 10, height: 10))
rect.moveBy(x: 10, y: 0)
print("Screen changed", rect)
rect.moveBy(x: -10, y: 0)
print("Screen changed", rect)

Output:

Screen changed Rectangle(origin: __lldb_expr_11.Point(x: 10, y: 0), size: __lldb_expr_11.Size(width: 10, height: 10))
Screen changed Rectangle(origin: __lldb_expr_11.Point(x: 0, y: 0), size: __lldb_expr_11.Size(width: 10, height: 10))

Seems surprisingly, even if we change something deep inside the struct, the didSet handler will get triggered.

Understanding why this works is key to understanding value types. Mutating a struct variable is semantically the same as assigning a new value to it. And even if only one property of a larger struct gets mutated, it's equivalent to replacing the entire struct with a new value.

A Struct is a value type. In other words, it's supposed to be immutable. So compiler ask you to write mutating in front of function that changes its variable

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

You can opt in to this behavior by placing the mutating keyword before the func keyword for that method.

Congratulation, you learned the basics of Mutating Keyword in Swift struct
Happy Coding 🎉

Read the original on Medium