This is kind of a stretch, but due to the reference vs value semantics of class
and struct
types, respectively, there is subtle difference in in the realization of a case where you want to make use of a type method (static
) to mutate a private property of the type, given an instance of the type has been supplied. Again, kind of a stretch, as this focuses on differences in implementation details, and not on a concrete difference between the two.
In the class
case, an immutable reference can be supplied to the static
method, which in turn can be used to mutate a private instance member of the type. In the case of the struct
, the instance of the type naturally needs to be supplied as an inout
parameter, as changing the value of an instance member of a value type also means changing the value of the instance itself.
class A {
private(set) var i: Int = 0
static func foo(_ bar: A) {
bar.i = 42
}
}
struct B {
private(set) var i: Int = 0
static func foo(_ bar: inout B) {
bar.i = 42
}
}
let a = A()
var b = B()
A.foo(a)
print(a.i) // 42
B.foo(&b)
print(b.i) // 42