Initialize @StateObject with a parameter in SwiftUI

前端 未结 5 1849
无人共我
无人共我 2021-01-03 20:29

I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an

5条回答
  •  花落未央
    2021-01-03 20:55

    I know there is already an accepted answer here, but I have to agree with @malhal on this one. I think the init is going to get called multiple times, which is the opposite behaviour of @StateObject intentions.

    I don't really have a good solution for @StateObjects at the moment, but I was trying to use them in the @main App as the initialisation point for @EnvironmentObjects. My solution was not to use them. I am putting this answer here for people who are trying to do the same thing as me.

    I struggled with this for quite a while before coming up with the following:

    These two let declarations are at the file level

    private let keychainManager = KeychainManager(service: "com.serious.Auth0Playground")
    private let authenticatedUser = AuthenticatedUser(keychainManager: keychainManager)
    
    @main
    struct Auth0PlaygroundApp: App {
    
        var body: some Scene {
        
            WindowGroup {
                ContentView()
                    .environmentObject(authenticatedUser)
            }
        }
    }
    

    This is the only way I have found to initialise an environmentObject with a parameter. I cannot create an authenticatedUser object without a keychainManager and I am not about to change the architecture of my whole App to make all my injected objects not take a parameter.

提交回复
热议问题