I have a simple task, but I am unable to find a solution. I'm making baby steps toward the eventual goal of creating an app that calculates annual earnings based on a fixed array of hourly pay rates that steadily increase yearly. The user will input the number of monthly hours worked and their company year group (defining which pay rate applies/where to start in the pay rate array).
My current baby step is to create a simplified verision: the hour pay rate is static.
The only error that my macOS Command Line Tool complies is "Function call causes an infinite recursion"
import Foundation
let pennyRoundingBehavior = NSDecimalNumberHandler(
roundingMode: .bankers,
scale: 2,
raiseOnExactness: false,
raiseOnOverflow: true,
raiseOnUnderflow: true,
raiseOnDivideByZero: true
)
func roundToNearestPenny(rate: Decimal, of dollarAmount: Decimal) -> Decimal
{
assert((0...100).contains(rate))
let x = ((dollarAmount * rate) as NSDecimalNumber)
return x.rounding(accordingToBehavior: pennyRoundingBehavior) as Decimal
}
enum EmploymentYears: Int, CaseIterable
{
case Year1, Year2, Year3, Year4, Year5, Year6, Year7, Year8, Year9, Year10
static var count:Int { allCases.count }
}
struct YearlyEarnings
{
var yearlyEarnings : Decimal = 0
init(monthlyHoursWorked: Decimal, payRate: Decimal)
{
let yearlyEarnings = roundToNearestPenny(
rate: payRate,
of: monthlyHoursWorked
)
self.init(monthlyHoursWorked: monthlyHoursWorked, payRate: payRate) // < -- error is here
}
}
extension Array where Element == YearlyEarnings {
subscript (index: EmploymentYears) -> Element { self[index.rawValue] }
}
func computeYearlyEarnings(
monthlyHoursWorked : Decimal,
rate : Decimal) -> [YearlyEarnings]
{
var yearlyEarnings: [YearlyEarnings] = []
yearlyEarnings.reserveCapacity(EmploymentYears.count)
let yearlyEarning = roundToNearestPenny(
rate: rate,
of: monthlyHoursWorked
)
return yearlyEarnings
}
var monthlyHoursWorked : Decimal = 160.0
var rate : Decimal = 20.0
let yearlyEarnings = YearlyEarnings(
monthlyHoursWorked: monthlyHoursWorked,
payRate: rate
)
for year in EmploymentYears.allCases
{
let curEarning = yearlyEarnings
print("Earnings for \(year)")
print(" $\(curEarning.yearlyEarnings)")
print()
}
I replaced
self.init(monthlyHoursWorked: monthlyHoursWorked, payRate: payRate)
with
self.init(yearlyEarnings: yearlyEarnings)
but that produced the following two errors:
"Extra argument 'yearlyEarnings' in call"
&
"Missing arguments for parameters 'monthlyHoursWorked', 'payRate' in call"