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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With