1

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?

1 Answer 1

1

This is because dice need to refer to your original struct and not a copy.

Try replacing:

func rollButtonPressed() {
    for dice in viewArray {
        dice.roll()
    }
}

with:

func rollButtonPressed() {
    for index in viewArray.indices {
        viewArray[index].roll()
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

OMG thank you! That was the answer. Works like a charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.