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

时间:2018-03-21 16:31:40

标签: arrays swift function loops core-data

我正在尝试迭代Core Data模型对象并进行如下计算。我无法弄清楚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循环,以便每个数组项只进行一次计算?

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

另请参阅documentation