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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With