GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

How to Address Swift6 when using UIDevice.current.userInterfaceIdiom

Forums > SwiftUI

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?

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

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.