Need some knowledge on Struct and specially property wrapper

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

    Same reason it’s printing “Advanced” after objXA was created, didSet is never called for a property when it is set in an init method.

    – 

  • @JoakimDanielson objXA.xb = “Swift” After this line still did set not called?.

    – 




  • 1

    It is called after objXA.xb = "Swift", but it is not called when you do XA(xb: "Quiz") or XA(xb: "Turing").

    – 

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.

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

Leave a Comment