Reputation: 139
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.
Upvotes: 1
Views: 494
Reputation: 54611
If I understood you correctly you can try map
+ reduce
.
Assuming the displayValue
is of type Int
(as you mentioned in the comments):
var viewArray: [Dice] = ...
let sum = viewArray.map(\.displayValue).reduce(0, +)
Assuming the displayValue
is of type String
you need to convert it to Int
first:
var viewArray: [Dice] = ...
let sum = viewArray.map(\.displayValue).compactMap(Int.init).reduce(0, +)
Upvotes: 1
Reputation: 139
Per @joakim I ended up solving this by creating:
let rollValues = viewArray.compactMap { Int($0.displayValue) }
let total = rollValues.reduce(0,+)
print("\(total)")
and then assigning that to the variable I needed to display. Worked like a charm!
Upvotes: 0