Search code examples
classswiftuiios13

How to Populate @State var using an Object?


I'm trying to "bind" information from a Class with State elements like this:

let people = People(name: "Jonnathan", firstSurname: "Bree")

@State private var name = people.name
@State private var firstSurname = people.firstSurname

but when I try to make this I have this error:

Cannot use instance member 'people' within property initializer; property initializers run before 'self' is available

or

Use of unresolved identifier 'self'

if a try to add .self before the object

Thank you so much!


Solution

  • Here is possible approach

    let people = People(name: "Jonnathan", firstSurname: "Bree")
    
    @State private var name: String
    @State private var firstSurname: String
    
    init() {
        _name = State<String>(initialValue: people.name)
        _firstSurname = State<String>(initialValue: people.firstSurname)
    }