Wizzardzz
Wizzardzz

Reputation: 841

Map Core Data model object to make calculations

I am trying to iterate through a Core Data model object and make calculations as follow. I can't figure out the for - in loops tho. Here every value is multiplied by every amount so the append and total are wrong. I only need each value to be multiplied to it's corresponding amount (for example bitcoin with 1.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)
}

How can I modify my for-in loops here so the calculations are only happening once for each array item?

Thanks!

Upvotes: 0

Views: 17

Answers (1)

Gori
Gori

Reputation: 347

When you have two arrays of the same length and in the same order, you can use Swift's zip function to combine the two into an array of tuples. In that case, your loop would change to

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

See also the documentation

Upvotes: 1

Related Questions