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


Joakim Weidenius
Joakim Weidenius
3,874 Points

Math commands swift

I'm just playing around, just learned basic functions. I constructed a simple calculator for BMI (body mass index) You should take your height times your height and divide that with your weight to get a BMI value. I'm having problem at row #2. I'm very unsure how i should write..

My code:

1 func dinBmi (weight: Double, length: Double) -> Double {

2 let bmi = (length * length) / weight

3 print(bmi)

4 return bmi


6 }

1 Answer

David Papandrew
David Papandrew
8,386 Points

Hi Joakim,

You are close to having the right answer. Main issue with your code is that the function is just going to take the function parameter values, perform a calculation and return a value.

When you call the function, you can then assign the function return value to a variable.

So your "let bmi = length * length...etc" should actually occur outside the function (when you call the function). All the function will do is return a value that it calculates from the supplied weight and height.

Here is the code:

//The function
func calculateBMI(weight: Double, length: Double) -> Double {
    return (length * length) / weight

//When you want to set a variable to the function output
let myBMI = calculateBMI(weight: 170, length: 60)