3

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.

ninjapro
  • 105
  • 5
  • What version of Xcode & Swift are you using? I plugged this in on Xcode 8.1 with Swift 3 and don't see the behavior you describe (running a simple view app in the iOS simulator). In my test, `"getter"` was printed once for each assignment to `value` in your test, regardless of the presence or not of parentheses. – par Oct 29 '16 at 07:33
  • 3
    Strange though, I do see it in an iOS playground on Xcode 8.1. Seems like a bug in the playground interpreter. – par Oct 29 '16 at 07:35
  • 1
    It seems that (for whatever reason) the Playground evaluates `b.a` in the second case once more and displays it in the result column as `A`. That does not happen with `_ = (b.a.value = 1)`. – Martin R Oct 29 '16 at 07:50
  • 2
    @MartinR Possibly related (slightly outdated): [DynamicType of optional chaining not the same as assignment](http://stackoverflow.com/a/37498376/4573247), specifically the section _"Wrapping expressions in parantheses escapes the runtime introspection of the Swift Playground?"_. It seems that the playground generally resolves expressions "one depth at a time" dynamically on-the-fly, to finally resolve the full expression a 2nd time. If we wrap the sub-expressions in paranthesis, the "dynamic part" of the playground expressions resolution is seemingly disabled. – dfrib Oct 29 '16 at 09:09
  • Playgrounds are notoriously buggy and unreliable – I would simply recommend steering clear of them in the first place, and instead test code in a full project. – Hamish Oct 29 '16 at 09:11

0 Answers0