正在加载视频...

视频加载失败

``` let viewModel = ViewModel(arg) _viewModel = StateObject(wrappedValue: viewModel) ``` Have you ever initialized a StateObject like this? 🤨 As it turns out, this code is actually incorrect and contains a very subtle bug 😱 Let me explain 😌

17,116 次观看 • 1 年前 •via X (Twitter)

10 条评论

Cocoanetics  的头像
Cocoanetics 1 年前

OMG I think I have this exact mistake in multiple places!!! Thank you for this!

Vincent Pradeilles 的头像
Vincent Pradeilles1 年前

It’s such a tricky one 🫠

Sau 的头像
Sau1 年前

Good catch!! I need to fix a couple of them 😂🔥🔥

1Dante 的头像
1Dante1 年前

Wow, I always do as in example, thanks for clarifying this potential issue.

Michael Schwab 的头像
Michael Schwab1 年前

Great content. It happens to be what I’m grappling with right now.

Jakob Joseph 的头像
Jakob Joseph1 年前

Init it in .task instead :)

Vincent Pradeilles 的头像
Vincent Pradeilles1 年前

That's also a possibility, but it does require making the values optional, right?

Nicolai Schneider 的头像
Nicolai Schneider1 年前

Thank you, I’m sure I’ve made this mistake here and there before!

José Gutiérrez 的头像
José Gutiérrez1 年前

Do you have the link for the article that you mention in the end?

Dong Nguyen 的头像
Dong Nguyen1 年前

I like simplicity, so I will create a static variable in a class that I call ‘Memory’ :D I don’t like viewModel with constructors that have additional parameters.

相关视频