Ula
Ula

Reputation: 177

Compare two arrays of Double Swift 4

Have two arrays of Doubles, I want to compare them and create a new array with result of the difference, but not sure how to create a loop for that. Please advise.

Example of the arrays here:

 var freshRates = [1.6,1.7,2.0]
 var oldRates = [1.5,1.4,1.9]
 var difference: [Double] = []

Upvotes: 1

Views: 541

Answers (2)

Reinier Melian
Reinier Melian

Reputation: 20804

var freshRates = [1.6,1.7,2.0]
var oldRates = [1.5,1.4,1.9]
var difference: [Double] = []

for (val1,val2) in zip(freshRates, oldRates){
    difference.append(val2 - val1)
}

debugPrint(difference)

Upvotes: 1

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

Zip the arrays to get an array of tuples, and then just use map to calculate difference for each pair:

var freshRates = [1.6,1.7,2.0]
var oldRates = [1.5,1.4,1.9]
var difference: [Double] = zip(freshRates, oldRates).map({ $0.0 - $0.1 })

Upvotes: 1

Related Questions