Loading video...

Video Failed to Load

Go Home

``` 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 views • 1 year ago •via X (Twitter)

10 Comments

Cocoanetics 's profile picture
Cocoanetics 1 year ago

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

Vincent Pradeilles's profile picture
Vincent Pradeilles1 year ago

It’s such a tricky one 🫠

Sau's profile picture
Sau1 year ago

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

1Dante's profile picture
1Dante1 year ago

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

Michael Schwab's profile picture
Michael Schwab1 year ago

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

Jakob Joseph's profile picture
Jakob Joseph1 year ago

Init it in .task instead :)

Vincent Pradeilles's profile picture
Vincent Pradeilles1 year ago

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

Nicolai Schneider's profile picture
Nicolai Schneider1 year ago

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

José Gutiérrez's profile picture
José Gutiérrez1 year ago

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

Dong Nguyen's profile picture
Dong Nguyen1 year ago

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.

Related Videos