WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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


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


@Obelix, thank you for your answer!!


Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.