PeterPan
PeterPan

Reputation: 744

StateObject as parameter for another object in init()

I'm trying to pass the StateObject user to the authenticationHelper but I can't since the IDE says that 'self is used before all stored properties are initialized', even though it is initialized at the beginning of the struct. I thought about moving the initialization of user to init() but again, I can't since it's a get-only property and it has to be initialized immediately. Is there a work around?

@main
struct Test: App {
    @StateObject var user: User = User()
    var authenticationHelper: AuthenticationHelper

    init(){
        self.authenticationHelper = AuthenticationHelper(user: user)
    }

    var body: some Scene {
        WindowGroup {
            LoginView(user: user)
        }
    } 
}

Upvotes: 0

Views: 701

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18904

Use computed property

struct Test: App {
    
    @StateObject var user: User = User()
    var authenticationHelper: AuthenticationHelper {
        return AuthenticationHelper(user: user)
    }
    
    init() {
    }
}

You can also use like this

struct Test: App {
    
    @StateObject var user: User
    var authenticationHelper: AuthenticationHelper
 
    init() {
        let user = User()
        self._user = StateObject(wrappedValue: user)
        self.authenticationHelper = AuthenticationHelper(user: user)
    }
}

Upvotes: 4

Related Questions