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

SOLVED: @State vs @StateObject in Apple's SwiftUI Landmark Tutorial

Forums > SwiftUI

Hello!

I've read Hacking with Swift's excellent description of the differences between @State and @StateObject here:

https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject

Ofcourse, shortly after, I found this example from Apple's Swift UI Landmark Tutorial that shook my confidence in the understanding of the guidance 😫

See Section 5 - Step 6

https://developer.apple.com/tutorials/swiftui/handling-user-input#Adopt-the-model-object-in-your-views

ModelData is an Observable class:

@Observable
class ModelData {
    var landmarks: [Landmark] = load("landmarkData.json")
}

and yet, the examples uses @State which I thought was for simple types, should be private only the View, etc...

struct LandmarksApp: App {
    @State private var modelData = ModelData()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(modelData)
        }
    }
}

I would have expected instead to see @StateObject (i.e.):

@StateObject private var modelData = ModelData()

So yeah...can anyone help me understand what I am missing?

   

The reason the Apple tutorial uses @State is because the tutorial is using the Observation framework Apple added at WWDC 2023. The @Observable before the class indicates that the model is using the Observation framework.

@Observable
class ModelData {
    var landmarks: [Landmark] = load("landmarkData.json")
}

The Observation framework does not use @StateObject. The Observation framework uses @State for both structs and classes.

If the tutorial was not using the Observation framework, then it would use @StateObject for a class, like you would have expected to see.

   

Aha! This is the first time I've come across the Observation framework in my learning. I think I've been using/reading the ObservableObject protocol and Observable macro interchangeably without realizing they are different...

I will check it out, thank you for the help!

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

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.