Это был бы лучший и более чистый подход к вашей проблеме.
struct Fruit {
var name: String
var stateCd: Int
var amt: Double
var cumulativeAvg: Double
}
Создайте другую структуру для хранения подсчета и среднего значения для определенного фрукта.
struct FruitStats {
var count: Double
var average: Double
}
Ведение словарякоторый отслеживает количество и среднее для каждого фрукта.
var fruitStats: [String: FruitStats] = [:]
var fruits = [
Fruit(name: "apple", stateCd: 0, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 200, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 1, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 300, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 0, amt: 100, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 1, amt: 100, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 0, amt: 400, cumulativeAvg: 0)
]
let newFruits = fruits.map { (fruit) -> Fruit in
var newFruit = fruit
var fruitStat = fruitStats[fruit.name, default: FruitStats(count: 0, average: 0)]
if fruit.stateCd == 0 {
fruitStat.average *= fruitStat.count
fruitStat.count += 1
fruitStat.average = (fruitStat.average + fruit.amt)/fruitStat.count
}
newFruit.cumulativeAvg = fruitStat.average
fruitStats[fruit.name] = fruitStat
return newFruit
}
for fruit in newFruits {
print(fruit.name, "\t", fruit.stateCd, fruit.amt, fruit.cumulativeAvg)
}
apple 0 100.0 100.0
apple 0 200.0 150.0
apple 1 100.0 150.0
apple 0 300.0 200.0
orange 0 100.0 100.0
orange 1 100.0 100.0
orange 0 400.0 250.0