Antonio Labra
Antonio Labra

Reputation: 2000

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!

Upvotes: 1

Views: 80

Answers (1)

Asperi
Asperi

Reputation: 257493

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)
}

Upvotes: 1

Related Questions