Swiftui 快捷菜单列表->;ForEach->;物品是出租的,所以我可以';不要改变一个值

Swiftui 快捷菜单列表->;ForEach->;物品是出租的,所以我可以';不要改变一个值,swiftui,swiftui-list,Swiftui,Swiftui List,如果我点击列表中的某个项目,我想更改“单击”的值(只需切换它)。。。 但出现此错误:“无法对不可变值使用mutating成员:'item'是'let'常量” 我想我是理解的,但我不知道如何修复“项目”在不允许的情况下 即使我在结构中创建一个变化的func来更改值也不起作用 谢谢你的帮助 struct Gamemode: Identifiable { var id: Int var name: String var clicked: Bool } struct Conte

如果我点击列表中的某个项目,我想更改“单击”的值(只需切换它)。。。 但出现此错误:“无法对不可变值使用mutating成员:'item'是'let'常量” 我想我是理解的,但我不知道如何修复“项目”在不允许的情况下 即使我在结构中创建一个变化的func来更改值也不起作用

谢谢你的帮助

struct Gamemode: Identifiable {
    var id: Int
    var name: String
    var clicked: Bool
}

struct ContentView: View {
    
    @State private var gamemodes: [Gamemode] = [
        Gamemode(id: 1, name: "example text", clicked: false),
        Gamemode(id: 2, name: "second example text", clicked: false),
        Gamemode(id: 3, name: "third example text", clicked: false),
        Gamemode(id: 4, name: "fourth example text", clicked: false)
    ]
    
    
    
    var body: some View {
        List {
            ForEach(gamemodes) { item in
                    VStack {
                        Text("Selection \(item.id)")
                        Text("\(item.name)")
                    }
                    .background(Color((item.clicked) ? .blue : .yellow))
                    .onTapGesture {
                        item.clicked.toggle()
                    }
            }
        }
    }
}

我不知道这是否是最好的解决方案,但也许是这样:

import SwiftUI

struct Gamemode: Identifiable {
    var id: Int
    var name: String
    var clicked: Bool
}

struct ContentView: View {

    @State private var gamemodes: [Gamemode] = [
        Gamemode(id: 1, name: "example text", clicked: false),
        Gamemode(id: 2, name: "second example text", clicked: false),
        Gamemode(id: 3, name: "third example text", clicked: false),
        Gamemode(id: 4, name: "fourth example text", clicked: false)
    ]



    var body: some View {
        List {
            ForEach(0..<gamemodes.count) { index in
                    VStack {
                        Text("Selection \(gamemodes[index].id)")
                        Text("\(gamemodes[index].name)")
                    }
                    .background(Color((gamemodes[index].clicked) ? .blue : .yellow))
                    .onTapGesture {
                        gamemodes[index].clicked.toggle()
                    }
            }
        }
    }
}
导入快捷界面
结构游戏模式:可识别{
变量id:Int
变量名称:String
变量:Bool
}
结构ContentView:View{
@国家私有var gamemodes:[Gamemode]=[
游戏模式(id:1,名称:“示例文本”,单击:false),
游戏模式(id:2,名称:“第二个示例文本”,单击:false),
游戏模式(id:3,名称:“第三个示例文本”,单击:false),
游戏模式(id:4,名称:“第四个示例文本”,单击:false)
]
var body:一些观点{
名单{
ForEach(0。。