So I have a struct of Dice that has a few properties attached to it. I want to be able to add them all together so I have one clean value. Here is the struct:
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)")
}
}
They are stored within an array here: @State var viewArray: [Dice] = [] and then displayed in an ForEach here:
ForEach(0..<viewArray.count, id: \.self) { index in
DiceView(dice: viewArray[index])
.onTapGesture {
self.viewArray.remove(at: index)
withAnimation(.spring()) {
}
}
}
The thing I'm trying to do is grab the displayValue of each item in the viewArray and add them together. What is the best way of doing so? I'm assuming I need to create some sort of array based on the property of displayValue and then add that array together, but I haven't come across it yet.
mapto get the property into an array and thenjoinedto make one string from the arraydisplayValueshould actually be anIntbut essentially yes. How would I use map to grab the displayValue property directly? The examples I see are for grabbing just the direct values, but since my array is a custom type how do I map the custom values?mapis to get a single property. Maybe you should read up on usingmap.