未在SwiftUI中使用@State属性包装器更新视图

未在SwiftUI中使用@State属性包装器更新视图,swift,swiftui,Swift,Swiftui,使用@State包装器不会更新视图。 视图在不使用@State包装器的情况下得到更新,但必须手动进行更新 import SwiftUI struct SwiftUIView: View { @ObservedObject var people: People var body: some View { VStack { ForEach(people.peoples){ person in HStack{

使用@State包装器不会更新视图。 视图在不使用@State包装器的情况下得到更新,但必须手动进行更新

import SwiftUI

struct SwiftUIView: View {
    @ObservedObject var people: People
    var body: some View {
        VStack {
            ForEach(people.peoples){ person in
                HStack{
                    Text("\(person.age)")
                    if person.ismale {
                        Text("Male")
                    } else {
                        Text("Female")
                    }
                    Button(action:{ person.age += 1}){
                        Text("Age+1")
                    }
                }
            }
        }
    }
}

struct Person: Identifiable{
    var id = UUID()
    @State var age: Int
    var ismale = true
}

class People: ObservableObject {
    @Published var peoples: [Person]
    init() {
        self.peoples = [
            Person(age: 10),
            Person(age: 12, ismale: false)
        ]
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView(people: People())
    }
}

由于某些原因,单击按钮时,视图没有任何更改

如果我把它改成

Button(action:{ **self.people.peoples[0].age += 1** }){
       Text("Age+1")
}
...

struct Person: Identifiable{
    var id = UUID()
    **var age: Int**
    var ismale = true
}
它会更新,但按钮不会是动态的。但是,如果我在ForEach循环中执行
person.age+=1
,而没有变量age的
@State
包装器

错误:“变异运算符的左侧不可变:'person'是'let'常量”


我想我理解Struct、Class、@State的意思。。。我想不是。。。感谢您提供的所有解决方案。

struct
是通过引用传递的,因此您不需要
@State',因为
observeObject`已经收到更新

这是
Person
struct

struct Person: Identifiable{
    var id = UUID()
    var age: Int
    var ismale = true
}
以及
SwiftUIView
。我删除了
If
语句,因此代码更干净一些

ForEach(people.peoples.indices, id: \.self){ index in
    HStack{
        Text("\(self.people.peoples[index].age)")
        Text(self.people.peoples[index].ismale ? "Male" : "Female")
        Button(action:{ self.people.peoples[index].age += 1 }){
            Text("Age+1")
        }
    }
}


谢谢你的解决方案。我真的不明白为什么
person.age+=1
在ForEach循环中不起作用,并输出错误:“mutating操作符的左侧是不可变的:'person'是一个'let'常量”。你能给我指一下正确的方向吗?非常感谢。它不起作用,因为在
ForEach
循环中,
person
是一个常量,不能修改。通常,闭包值是一个常量。