Reputation: 27
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
Reputation: 63321
You're really close! You just have a few small isuess:
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
).do
after else
. Just if { ... } else { ... }
int
, but the data type you're looking for is Int
. Identifiers, such as type and variable names, are case sensative.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
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