skip to Main Content
struct XA {

static var xa = "Advanced"

var xb: String {
    didSet {
        XA.xa = oldValue
    }
}}

var objXA = XA(xb: "Turing")
print(XA.xa) // Advanced
objXA.xb = "Swift"
print(XA.xa) // Turing

let objXB = XA(xb: "Quiz")
print(XA.xa) // Turing

i need to understand how these output coming in little bit depth. On the last line why its printing Turing not Swift.

2

Answers


  1. I think that the reason is that, a non static value don’t have an access to a static value inside a same Class or Struct

    Login or Signup to reply.
  2. The reason, as Joakim says in their comment, is that initializers do not invoke didSet/willSet. That’s by design.

    To Quote the Apple Swift eBook (emphasis added by me)

    The willSet and didSet observers of superclass properties are called
    when a property is set in a subclass initializer, after the superclass
    initializer has been called. They aren’t called while a class is
    setting its own properties, before the superclass initializer has been
    called.
    For more information about initializer delegation, see
    Initializer Delegation for Value Types and Initializer Delegation for
    Class Types.

    Excerpt From
    The Swift Programming Language (Swift 5.7)
    Apple Inc.
    https://books.apple.com/us/book/the-swift-programming-language-swift-5-7/id881256329
    This material may be protected by copyright.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search