Reputation: 11
I want to change the value of "clicked" if I tap on an item of the List (just toggle it) ... But this error comes: "Cannot use mutating member on immutable value: 'item' is a 'let' constant" I understand it right I think but I don't know how to fix that "item" ins't a let anymore Even when i create a mutating func in the struct to change the value doesn't work
Thank you for helping!
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()
}
}
}
}
}
Upvotes: 1
Views: 1593
Reputation: 159
I don't know if this is the best solution, but perhaps so:
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()
}
}
}
}
}
Upvotes: 2