Master Functions in Swift 4

Jayven N
iOS App Development
8 min readFeb 1, 2017

It’s about to get real.

Room for improvement is infinite. Improve a step at a time.

Purpose

Introduce all that is useful in using functions in Swift 4. Hopefully by the end of this article, you will have a deep understanding of using functions in Swift 4. Then have it be applied gracefully into your projects. The examples I give will be relatable. Basically using something we already know about to explain a something new.

I will keep things to its bone. Clear, concise, and practical.

That’s all for now. Open up Playground and let’s dive right in.

What are functions?

Functions are self-contained chunks of code that perform a specific task.

— Apple

We define functions to do a certain task which we can call upon later. Like an AC remote controller that has a defined function set to its ON button. We can call on that defined function by pressing the ON button and the AC will try to freeze you.

The Simplest Function of All Time

Let’s begin at ground zero and build our way up. This way we won’t miss a single thing. Right below me is an empty function, check it out:

func emptyFunction() {}

Which I can call within my code like this:

emptyFunction()

At the moment, it does ABSOLUTELY nothing which is GREAT.

This way we can dissect the function and understand every detail that goes into the making of a function in Swift. This next part is especially helpful when communicating with iOS developers, code interviewers and on paper.

To “command” what we just did to another person we would say define a function called “empty function.”

func → define a function

emptyFunction → name of the function

It Functions Now

Nowadays, a lot of us are addicted to Clash Royale. Maybe it’s just me. Anyways, let’s make an example out of a scenario from Clash Royale. We are going to define a function, call upon it, and pick up some things along the way. Let’s see it in action.

Define

Try and see if you can come up with a function based on the incoming descriptions from me. Define a function called “battle with” that takes in two parameters. The first parameter is the player’s name of type string. The second parameter is the battle deck that we want to use. Don’t worry if you did not get the parameters part, because I have not introduced it to you yet but will go into great details down the article.

Here is an example of how the function can be written:

func battleWith(playerName name: String, battleDeck deck: Int = 2) -> String {
return("Battle \(name) using deck number \(deck).")
}

Don’t freak out yet. Everything will be explained.

Ok let’s dissect the above function and see what these things are called:

( ) → parenthesis

playerName → argument label

name: String → a parameter of string value

battleDeck → argument label

deck: Int → parameter of int value

deck: Int = 2 → default value of two for the deck parameter

-> String → return of string value

We will explain more on what these things do after we see how it is called. I think it will make more sense if you see it from both the defining and calling perspectives. Also remember to put these codes in Playground and test it out yourself. Play around with it.

Call

You can call the functions in many different ways. Below are two examples of how you may want go about it:

battleWith(playerName: "BarbaricBeast_26")
// returns
// "Battle BarbaricBeast_26 using deck number 2."
battleWith(playerName: "Hulk Hogan", battleDeck: 1)
// returns
// "Battle Hulk Hogan using deck number 1."

The main difference between the first and second function call is the battleDeck parameter. When we battle BarbaricBeast_26, we use our default deck (2). We don’t need to explicitly set it because the function has set a default value of 2 to the deck parameter.

However, say we do battle Hulk Hogan, we may want to switch things up a little bit and use deck number 1. Why? Well because he is one rich motherf*cker. He also look like a hardcore gamer with that Hulkamania headband. So we will need to rage quit him if we want to win. Therefore, preferably battle deck number 1 where we store a lot of rockets, fireballs, and nukes. We will shut him down. Even if we do not, at least we trolled him. That’s the whole point of battle deck number 1 guys.

In-Out Parameters

Alright let’s expand upon rage quitting Hulk Hogan in Clash Royale. Butt! Before that, we beat the shit out of BarbaricBeast_26. As a result, we gained a bunch of good old golds. So let’s show off the in-out parameters with this scenario and pick up some helpful things along the way.

Define

We’re going to define a function that lets us add gold to our gold inventory. We will have an initial gold amount of say 1000 since our dada gave us a loan of a thousand bars of gold.

var myGoldInventory = 1000func addGoldTo(_ gold: inout Int) {
let increment = 100
gold += increment
}

Let’s see what we have yet to mention:

var → variable

_ → omitting argument label

inout → in-out parameter

let → constant

The first “hmm” you may encounter is the underscore. Basically, if you don’t want to see an argument label for a parameter, write an underscore instead of having an explicit argument.

Here are some variations of what I’ve just explained:

// Some variations of omitting argument labels
func exampleA(_ first: String, _ second: String) { }
exampleA("first", "second")
func exampleB(first: String, _ second: String) { }
exampleB(first: "first", "second")
func exampleC(_ first: String, second: String) { }
exampleC("first", second: "second")

The second “hmm” is the in-out parameter. To explain what it does, I would like you to imagine yourself doing the following: take a white rabbit, dip the white rabbit in a pot of Kale smoothies, and remove the rabbit from the Kale smoothies. Now the rabbit is green. Basically that is what the in-out parameter is all about. It is what you want to put into the function and have it be modified. Hence the name, “in out.”

If that did not make enough sense, read along and see how we call a function with the in-out parameter.

Call

We are going to call addGoldTo() on our gold inventory.

//Call
//Note: starting gold amount = 1000
addGoldTo(&myGoldInventory) //1100addGoldTo(&myGoldInventory) // 1200addGoldTo(&myGoldInventory) // 1300

Something new:

& → ampersand

We call the function most like how we did before. Only difference now is we placed an ampersand(&) in front of our variable to indicate that we are going to modify the variable that’s coming up next. Once we have the ampersand in place, we pass in our variable.

So say we won three games in a row and as our reward we get an increment of 100 gold each time we win. As a result, we would have accumulated 300 gold from the three winning games giving us a total 1300 gold in our inventory.

We go into a battle, we win, and we come with more gold.

Run Functions Inside Function

While we were accumulating gold, Hulk Hogan has been training his ass off in Clash Royale. Luckily, we are going to build a plan to beat his ass. What a great time to showcase “nested functions.”

First we are going to define some of things that we want to do to maximize our chance at whooping ass

func eatHealthy(food: String...) { }func drinkCoffee() { }func kickass() { }

Something new:

… → variadic parameter

A variadic parameter accepts zero or more values of a specified type. In our case, we set string as our specified type. Also note that each function is allowed up to one variadic parameter at most for whatever reason.

You may have also noticed that there is no argument label for the food parameter. Check out the following of codes below as they are made to clarify things up.

func anotherFunc(param1: String, param2: String) { }
anotherFunc(param1: "string", param2: "string")
func andAnotherFunc(_ param1: String, _ param2: String) { }
andAnotherFunc("something", "something")

Having no argument label is not the same as having an omitting argument label. If you leave out the argument labels when you define your function, the function will default an argument label that is the same name as the parameter label.

Great. Now let’s move on and have a look at what a nested function looks like.

func runPlan() {
eatHealthy(food: "sweet potato", "chicken breast", "boiled egg")
drinkCoffee()
kickass()
}
runPlan()

So basically we are just calling functions within a function. Now you may be wondering: “ Shit. When is a good time to use this?”

Ok here is the same example with comments to show a more practical example:

func runPlan() {
//if morning
eatHealthy(food: "sweet potato", "chicken breast", "boiled egg")

//else if afternoon
drinkCoffee()

//else
kickass()
}
runPlan()

You can think about this function like your personal trainer.

6 am: Eat eggs

12 am: Drink coffee

6 pm: Kick ass

Of course, we would have to pass in a value that indicate the time of the day. To avoid clustering and introducing many ideas at once, we will use comments to effectively get the point across.

The time parameter tell use what we need to do according to plans. Eat healthy in the morning. Load up on caffeine in the afternoon. Kick ass down the day. Sounds like a plan.

Func In Func

Imagine having a gun that can load different bullets for different on hit effect. The first type of bullet does damage to our. The second type heals to our target. And our target is a bad robot. It has a long history of eating iPhones. Beware, don’t say I didn’t warn ya.

Define

func shoot(_ target: inout Int, onHitEffect: (Int) -> Int) {
target = onHitEffect(target)
}

(Int) -> Int → function type parameter that takes an int and returns an int

Cool now that we have the main function. Let’s define two more functions where we can use.

func damage(_ hp: Int) -> Int {
return hp - 20
}
func heal(_ hp: Int) -> Int {
return hp + 20
}

Notice that the parameters value type and the return type of the two functions just created are the exact same as our shoot function’s parameter. They types have to be of the exact same unless we work with generics.

Call

Now we are going to define our bad robot as a mortal. Hence, as a variable. Then shoot two bullets that does damage to it. Each bullet does 20 damage as set by our damage function above. The bad robot’s HP is 80 after the first shot and 60 after the second.

Now because we are good people and good people are at least a bit sympathetic. Let’s shoot a bullet that heals the robot. This then runs the heals the robot back to 80 HP.

var badRobot = 100shoot(&badRobot, onHitEffect: damage) // badRobot = 80shoot(&badRobot, onHitEffect: damage) // badRobot = 60shoot(&badRobot, onHitEffect: heal)  // badRobot = 80

Last Remarks

I hope you have enjoyed and learned something valuable from this article. If you have then let me know by hitting that 👏🏻 button. Also, share this article so that your circle can make some knowledge gains too!

You can follow me on Medium for fresh articles. Connect with me on LinkedIn.

Lastly if you have any comment, question, or recommendation, feel free to post them in the comment section below!

Feel free to check out my recommended articles:

Introduction to API.AI

API.AI in Swift 3

--

--