映射核心数据模型对象以进行计算



我正在尝试遍历核心数据模型对象并进行如下计算。我无法弄清楚for - in循环。在这里,每个值都乘以每个数量,因此appendtotal是错误的。我只需要将每个value乘以它对应的amount(例如bitcoin1.00000000 (。

func updateWalletLabel() {
    var values : [Double] = []
    guard let items : [CryptosMO] = CoreDataHandler.fetchObject() else { return }
    let codes = items.map { $0.code! }
    let amounts = items.map { $0.amount! }
    print(codes) // ["bitcoin", "litecoin"]
    print(amounts) // ["1.00000000", "2.00000000"]
    // please note these values are in correct order (x1 bitcoin, x2 litecoin)
    for code in codes {
        for amount in amounts {
            let convertedAmount = Double(amount)!
            let crypto = code
            guard let price = CryptoInfo.cryptoPriceDic[crypto] else { return }
            let calculation = price * convertedAmount
            values.append(calculation)
        }
    }
    let total = values.reduce(0.0, { $0 + Double($1) } )
    print("VALUES", values) // [7460.22, 14920.44, 142.68, 285.36] (need [7460.22, 285.36])
    print("TOTAL:", total) // 22808.7 (need 7745.58)
}

如何在此处修改我的for-in循环,以便每个数组项的计算只发生一次?

谢谢!

当你有两个长度相同、顺序相同的数组时,你可以使用 Swift 的 zip 函数将两者组合成一个元组数组。在这种情况下,您的循环将更改为

for (code, amount) in zip(codes, amounts) {
    // Your calculation
}

另请参阅文档

最新更新