UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Why no setting of intial state?

Forums > SwiftUI

@speg  

I've been struggling to add an EditView to my list. I want to copy the list item into the EditView and then if the user saves changes, update the item.

The follow does not work, although it does compile. I guess you can't set the state during init? And then I do see the item in onAppear. Should I just keep the arugment passed in during intilization in another property and then update the state onAppear?

struct InitState: View {
    @State private var myState = "original"

    init(_ yourState:String) {
        self.myState = yourState
    }

    var body: some View {
        Text(myState)
            .onAppear {
            self.myState = "appear"
        }
    }
}

2      

You can set the value of your @State var in your init like this:

init(_ yourState:String) {
    _myState = State(initialValue: yourState)
}

3      

@speg  

Thanks @roosterboy! Just to clear my head and potentially help other newbies.. the _ prefix comes from synthiszed code that the compiler creates for us to store the property wrapper?

2      

The _ allows us to access the property wrapper object itself rather than the wrapped property.

So given...

@State private var myProperty = 1

myProperty gets us the integer being wrapped; _myProperty gets us the State wrapper around the integer.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.