Programming in Swift: Functions & Types

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

Part 1: Functions

07. Functions as 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: 06. Challenge: Overloads & Parameters Next episode: 08. Conclusion

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: 07. Functions as 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: 07. Functions as Parameters

Functions in Swift are simply another data type. You can assign them to variables and constants, and pass them into functions as arguments, just like you can any other type of value, like an Int or a String. Let’s see what that looks like in our Playground.

Let’s start by trying to store a function in a variable. First, create a new function called “add” that takes two Int parameters

func add(number1: Int, number2: Int)  {

}

It will also return an Int…

func add(number1: Int, number2: Int) -> Int {

}

and then just returns the sum of the two numbers from the function body.

  number1 + number2

Now, make a new variable called “function”, and assign it to the “add” function we just made.

var function = add

The function is now stored in this variable! Try calling function as you would have called add if there were no argument labels:

function(4, 2)

We get exactly the result we would expect in the sidebar! Now copy that add function, and change it to subtract two numbers:

func subtract(_ a: Int, _ b: Int) -> Int {
  return a - b 
}

And then set function to subtract

function = subtract

and give it a try

function(4, 2)

Now function is subtracting the arguments instead of adding them! That’s pretty cool!

But did you notice that we weren’t getting auto-complete to help us out when we called function? And we didn’t have to use argument labels, either!

Option-click on add. There’s our parameters, like we would expect, in the declaration and in this list of parameters underneath.

Now Option-click on function, here, to see the difference. We can see in the declaration that there’s an Int and an Int in the parameter list, and it returns an Int, but the parameter names are missing.

So, when we assign one of these functions to a variable, we’re losing some information. We’re just left with the type signature.

The really cool thing we can do, now that we know functions can be passed around like any other data, is pass a function into another function! Let’s make a function that could take either add or subtract as an argument.

Call it printResult

func printResult

because it will print the result of whatever operation we pass in. We’ll give it three parameters. The first one will be a function that represents an arithmetic operation, so I’ll call it “operate”:

func printResult(_ operate: 

Remember that functions, like tuples, are compound types. Their type is distinguished by a type signature, instead of a name.

The type signature of a function is made up of the types in its parameter list and its return type. So the type of operate would look like this:

func printResult(_ operate: 😺(Int, Int) -> Int

The parameter types are in parenthesis, followed by the return token and the return type.

Now, add two Ints to printResults parameter list so we have some values to pass into that operate function. Just call them a and b with no argument labels, to keep this example short.

func printResult(_ operate: (Int, Int) -> Int, _ a: Int, _ b: Int) {}

Then set up the body of the function. Make a constant to store the result of whatever operation was passed in

  let result = operate(a, b)

And call operate, passing in a and b. Then print result!

  print(result)

Now you can call printResult and pass in either add or subtract, and whatever numbers you want:

printResult(add, 4, 2)
printResult(subtract, 4, 2)

There’s 6 and 2 printed to the console! You can also pass in any other functions that have the same type signature. In this case, you could use some of the operators built into swift!

printResult(+, 8, 13)
printResult(-, 8, 13)
printResult(*, 8, 13)

The plus, minus, and multiply operators all take two Ints as parameters and return the result as an Int. So, they work perfectly in this printResult function.

Functions like this one, that use functions as parameter or return types, are called “higher-order functions”. There’s a way we might be able to improve this function. Remember back in Swift: Fundamentals, when you created a typealias for a tuple?

It looked something like this: a typealias lets you define a new name, or “alias”, for a type! You can do this for function types as well!

So, we can create a typealias to replace this type signature in the parameter list! To make one, type “typealias” and then the name you want to use.

typealias Operate

I called it “Operate”, and make sure its capitalized. Then paste in the type of function from the parameter list

typealias Operate = (Int, Int) -> Int

To use this fancy typealias, just put the name, “Operate”, wherever you would normally put that long type signature.

func printResult(_ operate: Operate, _ a: Int, _ b: Int) {

And you can see the playground runs just the same!