Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is didSet called when set inside an initializer?

Tags:

swift

swiftui

I'm playing around with SwiftUI and I have a class that looks something like this:

class Foo: ObservableObject {

    @Published var foo: Int! { // Implicit unwrapped optional
        didSet {
            print("foo")
        }
    }

    init() {
        self.foo = 1
    }
}

The didSet is always called. According to Apple docs it should not be called. Is there something special going on with the @Published property wrapper?

like image 220
Peter Warbo Avatar asked Nov 07 '22 11:11

Peter Warbo


1 Answers

All about types... Ok, let's consider code...

case 1: @Published var foo: Int

is actually

var foo: Int
var _foo: Published<Int>

so

init() {
    self.foo = 1 // << Initialization
}

case 2: @Published var foo: Int! (the same will be for @Published var foo: Int?)

is actually

var foo: Int!
var _foo: Published<Int?> // !! Not primitive - generics class, types differ

so

init() {
    self.foo = 1 // << Assignment of Int(1)
}

Thus, IMO, answer is yes, it is something special about @Published.

Note: You can see all picture in run-time if set breakpoint at self.foo = 1 line and using ^F7 (Control-Step Into) go by instruction for both cases... very interesting internals.

like image 195
Asperi Avatar answered Nov 15 '22 04:11

Asperi