Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 1: Functions

06. Challenge: Overloads & Parameters

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Advanced Parameters Next episode: 07. Functions as Parameters

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

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.

Transcript: 06. Challenge: Overloads & Parameters

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!