UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to calculate yearly earnings

Forums > Swift

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"

2      

Isn't this more what you are going for?

struct YearlyEarnings
{
    var yearlyEarnings  : Decimal = 0

    init(monthlyHoursWorked: Decimal, payRate: Decimal)
    {
        let earnings = roundToNearestPenny(
            rate: payRate,
            of: monthlyHoursWorked
        )
        self.yearlyEarnings = earnings
    }
}

Although, to be honest, it's not clear tome how what you have is a yearly value.

2      

@roosterboy Thank you! I wasn't sure where to multiply by 12 to make this a yearly result and not a monthly one. It seems to work with the following adjustment:

func roundToNearestPenny(rate: Decimal, of dollarAmount: Decimal) -> Decimal
{
    assert((0...100).contains(rate))

    let x = ((dollarAmount * rate) * 12 as NSDecimalNumber)
    return x.rounding(accordingToBehavior: pennyRoundingBehavior) as Decimal
}

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.