BeginnerQuestion: Cannot use instance member 'user' within property initializer; property initializers run before 'self' is available

Hello, I have a struct like:


struct User{

    var user1 = "Arnold"
    var user2 = "Max"

and then I have a SwiftUI-View where I want initialize a variable with this values, like this:

    var users =  User()

    @State var user = users.user1
// UI Code

I am starting with SwiftUI, I know to use MVVM-Pattern, but its only to understand why this gives me the error above and how to solve this kind of problems, where in the UI-View I want to dynamically change the value of a variable, for example with different buttons. For example changing the variable user from users.user1 to users.user2.

Thanks and perhaps somebody can give me a link where I can found more about this beginner problem... perhaps I have overseen something in the documentation.

Arnold

Answered by EricS in 676354022

There are at least two common choices:

  1. Set the variable in onAppear instead of on the same line as the declaration
  2. Set the variable in init, like _user = State(initialValue: users.user1)

See https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue

Accepted Answer

There are at least two common choices:

  1. Set the variable in onAppear instead of on the same line as the declaration
  2. Set the variable in init, like _user = State(initialValue: users.user1)

See https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue

BeginnerQuestion: Cannot use instance member 'user' within property initializer; property initializers run before 'self' is available
 
 
Q