TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Day 70: Question on setting an initial value for the @State property in the init method

Forums > 100 Days of SwiftUI

From the following code:

struct EditView: View {
    // ...
    @State private var viewModel: ViewModel
    // ...

    init(location: Location) {
        _viewModel = State(initialValue: ViewModel(location: location))
    }
}

I have a question about initializing the @State property in the init method. I noticed that directly assigning the value to viewModel like this viewModel = ViewModel(location: location) works just fine (I tested it). However, in this tutorial, Paul mentions that we should create an instance of the property wrapper, not just modify the data inside the wrapper. I'm wondering why directly assigning the value to viewModel works, even though Paul mentions that we should create an instance of the property wrapper.

Thank you very much,

Luis Montoya

   

See -> How NOT to initialize @State

www.swiftcraft.io/articles/how-to-initialize-state-inside-the-views-init-

This article adds some information. But also includes some contradictions to what @twoStraws says in his video.

2      

@Obelix, thank you for your answer!!

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.