thePilot
thePilot

Reputation: 27

code If number greater than x, make y = amount

I am trying to make a iOS app which calculates annualized income and 401(k) contribution. I can't figure out how to code the func so it limits the 401(k) contribution at 18500 despite the percentage of income put in by the employee. I know this is super basic but I've been working on it for hours and I can't seem to get it to work. Any help is appreciated.

func your401 () -> int {
    if employee401kContribution < 18500 {
        return employee401kContribution
    }
    else do {return = 18500 }
}

Upvotes: 0

Views: 47

Answers (2)

Alexander
Alexander

Reputation: 63321

You're really close! You just have a few small isuess:

  1. You don't put an equals sign after return. It's a special form, and it doesn't use the equals sign. Just return 18500 (or you could even style it as return 18_500).
  2. You don't put do after else. Just if { ... } else { ... }
  3. The return type is int, but the data type you're looking for is Int. Identifiers, such as type and variable names, are case sensative.
  4. your401 is not a descriptive name. You should name this function to more clearly communicate exactly what it does.

Here's what you get if you fix it up:

func nameMeBetter() -> Int {
   if employee401kContribution < 18_500 {
       return employee401kContribution
   } else {
       return 18_500
   }
}

Even simpler, you can implement this with Swift.min(_:_:):

func nameMeBetter() -> Int {
   return min(employee401kContribution, 18_500)
}

Upvotes: 1

Code Different
Code Different

Reputation: 93181

You can do this in a few ways

// Closest to your original code
func your401() -> Int {
    if employee401kContribution < 18500 {
        return employee401kContribution
    } else {
        return 18500
    }
}

// A shorter version using the conditional ternary operator
// return (condition) ? (value if true) : (value if false)
func your401() -> Int {
    return employee401kContribution < 18500 ? employee401kContribution : 18500
}

// Most compact of all. This stays close to the English description
// "the employee's 401k contribution or 18500, whichever is less"
func your401() -> Int {
    return min(employee401kContribution, 18500)
}

Upvotes: 1

Related Questions