Why a var
struct
becomes let
when passed to a function?
struct S {
var i: Int = 1
}
// this won't compile...
func changeS(s: S) {
s.i *= 2 // illegal: left side of mutating operator isn't mutable: 's' is a 'let' constant
}
var s = S() // struct defined as `var`
s.i *= 2 // and indeed this is legal
CodePudding user response:
Because struct
are not reference-type, but value-type.
This means that every time you pass a struct to another function, it gets copied into a new immutable struct (so it's a let
).
If you change the value of the passed struct within a function, the original struct will not be affected, unless you tell the compiler that the param of the function is inout
.
struct S {
var i: Int = 1
}
// this will compile now with inout keyword
func changeS(s: inout S) {
s.i *= 2 // now this is mutable and its change will be transferred back to the original struct.
}
var s = S() // struct defined as `var`
s.i *= 2 // and indeed this is legal
changeS(s: &s) // notice the & before the var, it tells the compiler to pass the struct as inout param
CodePudding user response:
Function input arguments in Swift are immutable by default. You need to mark the input argument as inout
if you want to be able to mutate it inside the function.
struct S {
var i: Int = 1
}
func changeS(s: inout S) {
s.i *= 2
}
var s = S()
s.i *= 2
changeS(s: &s)
For more info, read the functions chapter of the Swift Language Guide.