Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between "mutating" function and "inout" parameters in Swift?

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.

like image 591
subin272 Avatar asked Mar 27 '19 07:03

subin272


1 Answers

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
like image 84
Sweeper Avatar answered Oct 10 '22 02:10

Sweeper