In this demo, you’ll start implementing your solution to the puzzle. You’re going to implement a function that takes two input parameters and returns the sum of the numbers between the two inputs.
Open Xcode on your Mac and create a new playground. Start by creating the function declaration:
func calculateSum(minValue: Int, maxValue: Int) -> Int {
}
Calculating the sum is straightforward. You want to loop through all the numbers between the two inputs, adding them to a variable that holds the total and then returning that sum variable after the loop. Add this code in the function:
var sum = 0
for i in minValue...maxValue {
sum += i
}
return sum
If you’ve never seen it before in other programming languages, the line sum += i is a shortcut for sum = sum + i. Because it’s so common to want to add a value to a variable without making a new variable, this shortcut was introduced. All the basic math operations have a version: -=, *=, +=, and /=.
Try your new function with different input values:
calculateSum(minValue: 0, maxValue: 10)
calculateSum(minValue: 0, maxValue: 100)
Run your playground and observe the results in the right pane.
This solution gets the job done, but is it the best solution?
In the next part, you’ll learn how to measure the performance of your code so you can judge for yourself if this solution is the most efficient or not.