[英]Add elements of custom array SwiftUI
So I have a struct of Dice
that has a few properties attached to it.所以我有一个
Dice
结构,它附加了一些属性。 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:它们存储在此处的数组中:
@State var viewArray: [Dice] = []
然后在此处显示在 ForEach 中:
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.我正在尝试做的事情是获取
displayValue
中每个项目的viewArray
并将它们添加在一起。 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.我假设我需要根据
displayValue
的属性创建某种数组,然后将该数组添加在一起,但我还没有遇到过。
If I understood you correctly you can try map
+ reduce
.如果我理解正确,您可以尝试
map
+ reduce
。
Assuming the displayValue
is of type Int
(as you mentioned in the comments):假设
displayValue
是Int
类型(正如您在评论中提到的):
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:假设
displayValue
是String
类型,您需要先将其转换为Int
:
var viewArray: [Dice] = ...
let sum = viewArray.map(\.displayValue).compactMap(Int.init).reduce(0, +)
Per @joakim I ended up solving this by creating:根据@joakim,我最终通过创建解决了这个问题:
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!
像魅力一样工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.