Leave a rating/review
Notes: 06. Challenge: Overloads & Parameters
Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.
Are you ready for your next challenge? You’ll find it on page 4 of the Playground for this part of the course. Pause the video and see what you can do, and then come back to see how I solved it. Have fun!
First up: “Write two possible overloads for the function below.”
Well, I can easily remove the argument labels to create one overload…
func multiply(😺_ number: Int, 😺_ multiplier: Int) -> Int {...
I can also create an overload that multiplies Doubles instead of Ints
func multiply(number: 😺Double, multiplier: 😺Double) -> 😺Double {...
For challenge #2, I need to get rid of the overloads and use a default value, instead. This second function is assuming the number you want to multiply is always 1
So I can easily combine these two functions by giving the number parameter a default value of 1!
func printMultipleOf(multiplier: Int, number: Int😺 = 1🛑) {...
And then if I comment out the first two functions… When we run the playground, these function calls still work as expected!
The last challenge was to change this update function so that it can modify a parameter. In this case, the score parameter is the one we want to modify.
To do that, first add the inout keyword right before the type of the score parameter.
func update(score: 😺inout🛑 Int, withPoints points: Int) {
Then I also need to update the function call, to say that this value might be mutated by the function.
update(score: 😺&🛑score, withPoints: 100)
Now we can run the playground… And see that this score variable has been updated!