Is it okay to use @State to store object ref instead of @StateObject

Hi,

I want to display a sheet bound to an object using

.sheet(item: $someObject content: <#T##(Identifiable) -> View#>)

However if item is a class we can't use @StateObject var someObject: SomeObject? because an optional cannot conform to observable object.

As I don't have any changing property and do not need the view to be refreshed once passed to the sheet I used @State and it seems to be working fine.

Here is a minimal example of what I'm doing.

import SwiftUI

class SomeObject: Identifiable {
  let id = 1
  let content = "Hello world"
}

class SomeObjectStore {
  static let shared = SomeObjectStore()

  var objects = [SomeObject()]

  private init() {}
}

struct ContentView: View {
  @State private var someSheetPresentedObject: SomeObject?

  var body: some View {
    Button("Open view") {
      someSheetPresentedObject = SomeObjectStore.shared.objects.first
    }
    .sheet(item: $someSheetPresentedObject) { someObject in
      Text(someObject.content)
    }
  }
}

It seems okay because SwiftUI only needs to know if there is a reference to someSheetPresentedObject or not to present the sheet. I know that the Text won't be updated if SomeObject.content changes but I'm only displaying it once so it's not an issue.

My question is: is it okay to do this for this specific case ?

Anyway, your objects properties are let, so they cannot change…

That's seems OK as is, but may break if you change to var in the future…

You may have read this already: https://levelup.gitconnected.com/state-vs-stateobject-vs-observedobject-vs-environmentobject-in-swiftui-81e2913d63f9

Indeed in the example the properties are let so they cannot change at all. In my project it's a bit more complicated but the principle stays the same, properties are only passed once in the view constructor.

Thank you for the linked article.

Is it okay to use @State to store object ref instead of @StateObject
 
 
Q