You do not show the definition of your Item
object. But you're right, you could improve your solution.
For example:
ForEach(listItems, id: \.self) { item in
let valueFloat = (item.value as NSString).doubleValue // Stop! Refactor and move to Item struct
let formattedFloat = String(format: "%.2f", valueFloat) // Stop! Refactor and move to Item struct
Text("\(item.name) \(formattedFloat)")
}
You are creating Text
views for each Item
object in your listItems
array.
Consider moving ALL this code into your Item struct. That is, consider adding computed vars to your Item struct.
struct Item {
// Previous declarations
//==== computed var ======
var itemVarAsFloat : Float {
(self.value as String).doubleValue // Seems awkward
}
var formattedVar: String {
String(format: %.2f", itemVarAsFloat)
}
}
Then your view is greatly simplified! In your view, try to DECLARE what you want to see. Let other structs do the computing.
ForEach(listItems, id: \.self) { item in
Text("\(item.name) \(item.formattedVar)") // DECLARE what you want to see.
}