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

Confused with underscore in init, assigning a default value, and .onAppear

Forums > 100 Days of SwiftUI

In the CoreDataProject project and in the BucketList project, Paul has us using the underscore in a View's initializer to assign some value to a State, StateObject, or FetchRequest. I'm somewhat confused why we're doing this.

I've tried making some more basic code to see what's going on. It's seems assigning a default value by doing: @State private var text = "Hello world!", using .onAppear: .onAppear { text = "Hello, galaxy!"}, or using the struct's initializer achieve the same thing and set a value for the text property when the view is loaded. Up to this point, I've mostly used .onAppear to set things when the screen loads but maybe the initializer is a better place to set these things. Can someone please explain what the benefit is of using one approach over another?

struct ContentView: View {
    @State private var text = "Hello world!"

    var body: some View {
        NavigationView {
            Form {
                Text(text)
            }
            .onAppear { text = "Hello, galaxy!"}
        }
    }
    init() {
        _text = State(initialValue: "Hello, solar system!")
    }
}

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.