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

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!")
    }
}

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, 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!

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.