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 ?