Home > OS >  Swift: calculate percentage for each element in array
Swift: calculate percentage for each element in array

Time:10-25

I set an array for storing income values per month in USD:

let incomePerMonthArray = [0.0, 1.0, 2.0, 3.0]

Also I set constant, which represents tax in %:

let taxRate = 10.0

I need to calculate tax in USD for each element in incomePerMonthArray and store it in a new array.

What is the best way to do that?


I successfully used following function for single values:

//Calucate percentage based on given values
public func calculatePercentage(value:Double, percentageVal:Double) -> Double {
    let val = value * percentageVal
    return val / 100.0
}
let taxInUSD = calculatePercentage(value: Double(incomePerMonth), percentageVal: taxRate)

But it doesn't work with arrays.

CodePudding user response:

Use a map statement.

let taxesPerMonth: [Double] = incomePerMonthArray.map { calculatePercentage(value: $0, percentageVal: taxRate) }

That will call your calculatePercentage(value: percentageValue:) function on every element in yoru income array, and the result will be a new array containing the taxes for each income.

Note that maintaining 2 separate arrays is fragile. it would make more sense to create a struct that contains an income and a tax value, and populate the tax value with calls to your function (and perhaps a map statement that mutates your struct and applies tax values to each struct.)

  • Related