正在加载视频...

视频加载失败

I have come across something with the Observation framework that is confusing me so if there are any #SwiftUI Observation framework experts out there that can explain this to me, I would be forever grateful. Why I don’t have to define the object as a State object?

10,172 次观看 • 2 年前 •via X (Twitter)

8 条评论

Maxim Bazarov 的头像
Maxim Bazarov2 年前

That’s because SwiftUI automatically tracks any observable properties that a view’s body reads directly.

StewartLynch 🇨🇦 的头像
StewartLynch 🇨🇦2 年前

Thanks Maxim. Not sure how I missed that.

Parsa 的头像
Parsa2 年前

The first code's equivalent with the old combine stuff is marking the MyObject as an ObservedObject. This binds it to the lifecycle of the struct, meaning that the property changes retrigger the body, and any re-invocation of the ContentView itself would create a new MyObject. It's due to how the new Observable grabs references of the component that is listening to a certain keypath (\.value in this case) and notifies them of the change.

Igor Tarasenko 的头像
Igor Tarasenko2 年前

Expand the macro. This will help in your understanding.

DSWH 的头像
DSWH2 年前

The macro sets state. The protocol expects you to set state

Andres Raigoza 👨‍💻 的头像
Andres Raigoza 👨‍💻2 年前

This shows how efficient the macro is compared to ObservableObject, it runs the body but it doesn’t recreate the View

DSWH 的头像
DSWH2 年前

The macro is new. I’m still working on a m1 :(. Older Xcode.

DART Meadow 的头像
DART Meadow2 年前

I think the increment operator syntax: += , is colliding -for itself as a variable in the production code below the observable code block, you might need additional syntax for the observable API.

相关视频