Home > front end >  Give @State private var a variable Array as initial value
Give @State private var a variable Array as initial value

Time:10-05

I have this @State private var which is an Array of strings and changes values when buttons are tapped. But as an initial value, I want it to take an array of strings that is variable.

@ObservedObject var News = getNews()
@State private var newssitearray : Array<String>

init() {
    _newssitearray = State(initialValue: News.data.map {$0.newsSite})
}

What I did above gives the error:

self was used before all stored properties are initialized.

CodePudding user response:

Do everything in init, like

@ObservedObject var News: YourTypeOfNewsContainer      // << declare only
@State private var newssitearray : Array<String>

init() {
    let news = getNews()   // << assuming this is synchronous

    // use local var for both properties initialization
    self.News = news
    self._newssitearray = State(initialValue: news.data.map {$0.newsSite})
}

Important: if you getNews is asynchronous, then it cannot be used either in property initialisation or init itself - think to do this in .onAppear

  • Related