我在初始化数组时遇到问题:
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)
}
}
就像我期望的那样,在我的初始化例程中,索引设置为[“ E”,“ F”]而不是[“ A”,“ B”]。发生什么事了?
答案 0 :(得分:4)
仅在声明时不初始化状态(因为它只初始化一次,然后在视图生命周期内起作用,即在body
中起作用)
@State private var indexes: [String] // << only declare
init(store: ProjectStore, searchText: Binding<String>)
{
...
self._indexes = State(initialValue: ["C","D"]) // initialise !!
答案 1 :(得分:1)
@State是属性包装器,这意味着它会获取包装值的输入然后进行修改,因此您永远不要在init中设置@State var,如果您确实想在init中对其进行初始化,则必须直接设置@State var使用@State的init,因为@State是带有@语法糖的结构。更改
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)
}
至:
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)
}