NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: I don't understand how @State works

Forums > 100 Days of SwiftUI

I'm trying to initialize a @State variable in the init() but that doesn't work, and I don't understand why. Here's the code:

struct ContentView: View {

    @State private var message = "empty"

    init() {
        message = "Test"
    }

    var body: some View {
        Text(message)
            .padding()
    }
}

The app displays "empty". so how do I initialize a variable?

   

@State private var message: String

and leave your init() should do it.

1      

Thank you!

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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.