I've been trying to remove all Swift 5.x dependencies, the last main one is my usage of .userInterfaceIdiom to change font sizes based on device I am on. I have tried to create a simple class that looks like this -
@MainActor
class IsIphone : ObservableObject {
@Published var iPhone : Bool = false
@MainActor
init() {
if UIDevice.current.userInterfaceIdiom == .phone {
self.iPhone = true
}
}
}
And then injecting that into the environment at app launch via -
@State var isIphone = IsIphone()
However this is generating the error -
swift:14 Accessing Environment<Optional<Color>>'s value outside of being installed on a View. This will always read the default value and will not update.
Which is very weird as I am not addressing <Optional<Color>>
at all.
I also get the warning on the same line -
.swift:14:16 Main actor-isolated default value in a nonisolated context; this is an error in Swift 6
Which now moved the error from each location in the code to the initial instansiation.
Additionally, in those views where I was using the .userInterfaceIdiom in the initializer to make a decision in the init() I now get compiler errors of trying to access other variables before their definition, e.g.
@EnvironmentObject var isIphone: IsIphone
private var gridLayout: [GridItem]
init() {
if isIphone.iPhone { // UIDevice.current.userInterfaceIdiom == .phone || UIDevice.current.userInterfaceIdiom == .vision
self.gridLayout = [
GridItem(.adaptive(minimum: 160), spacing: 10, alignment: .center)
]
} else {
self.gridLayout = [
GridItem(.adaptive(minimum: 320), spacing: 20, alignment: .center)
]
}
}
returns the error Variable 'self.gridLayout' used before being initialized
btw, I simplified the init() for this post as I am setting up Query() and other items in the init.
What is the correct way to approach this problem?