I'm trying to build a dice roller where I can add dice to an array, then roll each dice with a random number across the array (so each die has a different number). My current Dice struct is here:
struct Dice: Identifiable, Hashable {
var id = UUID()
var displayValue: String
var initialValue: Int
var endingValue: Int
mutating func roll() {
let randomInt = Int.random(in: initialValue..<endingValue)
displayValue = "\(randomInt)"
print("Initial: \(initialValue), EndingValue: \(endingValue), Display: \(displayValue)")
}
}
and in the main view I have an array of : @State var viewArray: [Dice] = []
I have a SwiftUI button that "rolls" the dice:
Button(action: rollButtonPressed, label: { Text("Roll Dice") })
That triggers this function (where I have my error):
func rollButtonPressed() {
for dice in viewArray {
dice.roll()
}
}
The issue I'm running into is that on the line with dice.roll it throws an error of Cannot use mutating member on immutable value: dice is a let constant
I'm not sure how to fix this, my assumption is that I need to create a loop that triggers the roll() function of each Dice struct to randomize the number they will display, but only trigger once. What should I be looking to fix?