I have the following code:
class A {
var value = 1
}
struct B {
private var _a: A
var a: A {
get {
print("getter")
return _a
}
}
init(a: A) {
_a = a
}
}
let b = B(a: A())
(b.a).value = 10
// print "getter" once
b.a.value = 10
// print "getter" twice
If I simply read a.value
, getter is called once. The question is what difference is between (b.a).value =
and b.a.value =
? And why does Swift behave like this?
The same happens if B
is class instead of struct.
"getter"
was printed once for each assignment tovalue
in your test, regardless of the presence or not of parentheses.b.a
in the second case once more and displays it in the result column asA
. That does not happen with_ = (b.a.value = 1)
.