5

As per Swift documentation both mutating and inout keywords are used to modify the value types from within a function. Is there any difference between "mutating" and "inout" and any special case where we need to use either of them.

subin272
  • 601
  • 5
  • 21

4 Answers4

15

mutating marks a method. inout marks a parameter. They are completely different things.

Methods marked with mutating can mutate self i.e. set properties of self, reassign self etc.

struct Foo {
    var foo: Int

    mutating func mutate() {
        foo += 1 // this is mutating self
    }
}

Parameters marked with inout basically become var variables, as opposed to let constants. You can change them, and the changes will also reflect on the caller's side.

func f(_ x: inout Int) {
    x = 10
}

var a = 1
f(&a)
print(a) // 10
Sweeper
  • 145,870
  • 17
  • 129
  • 225
  • `Parameters marked with inout basically become var variables, as opposed to let constants. ` — quite a bit disagree, because `Swift` used to have `var` *mark* for function parameters, and it was different thing. Parameters with `var` were allowed to mutate, but all the changes never left scope of function, changes of `inout` params were *put back* into variable passed into function. – user28434'mstep Mar 27 '19 at 08:51
  • @user28434 that’s why I also wrote the next sentence. – Sweeper Mar 27 '19 at 08:52
  • And I quoted part about `basically become var variables`. Because there were both `var` and `inout`, and they were different things, calling one using keyword of another is confusing. – user28434'mstep Mar 27 '19 at 08:55
2

For me I see difference just in places where they are used.

Parameter marked with inout keyword allows you to pass your value to any method similary as reference

func square(inout num: Int) { 
    num = num * num
}

In contrast to it, method marked with mutating keyword is used in type scope and allows you to change value itself from this method

extension Int {

    mutating func square() {
        self = self * self
    }

}
Robert Dresler
  • 10,121
  • 2
  • 15
  • 35
2

Value types' instance methods cannot change the value type's properties (or value itself), unless they are marked as mutating.

Functions of any kind cannot change their parameters (and have the change propagate outside the function) unless those parameters are marked as inout.

They do a similar job, but in different contexts.

Amadan
  • 169,219
  • 18
  • 195
  • 256
1

inout:- It means that modifying the local variable will also modify the passed-in parameters. Without it, the passed-in parameters will remain the same value.

mutating:-The properties of value types cannot be modified within its instance methods by default. In order to modify the properties of a value type, you have to use the mutating keyword in the instance method.