Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How can I add an if statement to a function?

func calculateFieldGoalPercentage (madeShots madeShots : Float, attemptedShots : Float) ->Float {

    return (madeShots / attemptedShots) * 100

}


calculateFieldGoalPercentage(madeShots: 16, attemptedShots: 30)

I've created a function that will calculate a player's field goal percentage. I want to add an if statement that returns the percentage along with the string "Great Job!" if it is greater than 50 and "You need to practice more!" if less than 50. How would I go about doing this? I'm having issues with the return type, combining a string with a float.

2 Answers

Hi there,

Here's one solution for your requirement. It isn't particularly pretty and I'm sure it could be simplified but it works, I think.

func calculateFieldGoalPercentage(madeShots: Float, attemptedShots: Float) -> (Float, String){
    var message: String
    if madeShots / attemptedShots < 0.5 {
      message = "Train harder!"
    } else {
      message = "Good work!"
    }
    var goalResult: Float = (madeShots / attemptedShots) * 100
  return (goalResult, message)
}

var result = calculateFieldGoalPercentage(16, 30)

result.0
result.1

This returns a tuple. So, assign the returned value of the function to a variable and access each side of the tuple using dot notation, like at the end of the code above.

Let me know if this does what you want or if it needs work!

Cheers,

Steve.

Thanks a lot for your response. I'm going to look this over.

No problem. Let me know if you need more than this.

The solution here is placed all in one method. Without knowing what your implementation plans are, I can't say whther that's the best way to solve the issue or not. It may be better having a single method, and manipulating the number elsewhere; I don't know.

The only oddity here is the tuple that the method returns. This is a data pairing defined as the return type of the method. You use the tuple by catching the method's returned value. You can then pull the tuple apart with the dot notation and use each side of the pairing however suits.

Let me know if I can add any further clarity.

Steve.