3

I'm having a problem initialising my arrays in my view:

struct ProjectList: View
{
    @ObservedObject var store: ProjectStore
    @Binding var searchText: String

    @State private var query: [Project] = []
    @State private var indexes: [String] = ["E","F"]
     
    init(store: ProjectStore, searchText: Binding<String>)
    {
        self.store = store
        self._searchText = searchText
        self.query = []
        self.indexes = ["C","D"]
        indexes = ["A","B"] //store.getIndexes(search: searchText.wrappedValue)
        print (indexes)
    }
}

indexes is being set to ["E","F"] not ["A","B"] in my init routine as I would have expected. What is happening?

iphaaw
  • 6,764
  • 11
  • 58
  • 83

2 Answers2

5

Just don't init state when declare (because it is initialised only once and then works during view life-time, ie in body)

    @State private var indexes: [String]        // << only declare

    init(store: ProjectStore, searchText: Binding<String>)
    {
        ...
        self._indexes = State(initialValue: ["C","D"])  // initialise !!
Asperi
  • 228,894
  • 20
  • 464
  • 690
1

@State is property wrapper that means it takes the input of wrapped value and then modifies it, you should never set @State var in init, you have to set @State var directly if you really wanna initialize it in init you have to use init of @State since @State is a struct with syntactic sugar with @. Change

 init(store: ProjectStore, searchText: Binding<String>)
    {
        self.store = store
        self._searchText = searchText
        self.query = []
        self.indexes = ["C","D"]
        indexes = ["A","B"] //store.getIndexes(search: searchText.wrappedValue)
        print (indexes)
    }

to :

 init(store: ProjectStore, searchText: Binding<String>)
    {
        self.store = store
        self._searchText = searchText
        self.query = []
        self.indexes = ["C","D"]
        indexes =  State(initialValue: ["C","D"]) //changed value
        print (indexes)
    }
sriram hegde
  • 2,301
  • 5
  • 29
  • 43