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.

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, 2016 at 7: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, 2016 at 7: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, 2016 at 7:50
  • 2
    @MartinR Possibly related (slightly outdated): DynamicType of optional chaining not the same as assignment, 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, 2016 at 9: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, 2016 at 9:11

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.