Swift

Functions

Simplifying our code with functions

What is a function?

A function is a named part of your code that carries out a specific task or set of tasks. A function is first defined (decide what the function actually does) and must then be called. When a function is “called”, we are asking the computer to perform the tasks we already assigned to the function.

Functions allow us to reuse a set of commands (multiple lines) with just a single line of code (the line to call the function). This makes our code much shorter. In addition, the code can be given a descriptive name through the function’s name to give readers a clearer understanding of what is going on. They are like mini-programs. Just like programs take in an input and give out an output, all under a descriptive name, functions can take in input through ‘parameters’, and output information too.

In a quick summary, the point is to avoid repetition of code. This is a long section, but is key to making sure you are great at Swift.

Writing a basic function

Writing a function in Swift is very easy to do. We just need to write func, give it a name, add (), and put the rest of our code in curly braces.

func sayHello() {
    print("Hello!")
}
        
sayHello()
sayHello()

As you can see, whenever we 'call' sayHello(), it prints out “Hello!”. We can replace this with lots of different code, and it makes it easier for us to write large sections of code.

Parameters

We can also feed information into our function, through the (). We just need to give a name, and a type. The function below prints a different message per variable.

func myFavoriteColor(color: String) {
    print("My favorite color is \(color)")
}
    
myFavoriteColor(color: "Red")
myFavoriteColor(color: "Blue")
    
func allAboutMe(name: String, age: Int) {
    print("My name is \(name), and I am \(age) years old!")
}
    
allAboutMe(name: "Greg", age: 14)

More on Parameters

Notice in the functions, when we call them, we have to write the name of the variable, then the value. But we can actually play around with this. There are lots of different ways we can rename parameters for when they are called.

func countLetters(in word: String) { // when we add in, we rename the parameter when it's called. This is closer to how english works. We could use anything to replace in, but inside the function, we still use word
    print("The word \(word) has \(word.count) letters.")
}
    
countLetters(in: "STEMpump")
    
func favoriteIceCream(_ flavor: String) { 
    // when we add _ before the parameter name, we don't need to do anything except write the value when calling the function
    print("My favorite ice cream flavor is \(flavor)")
}
favoriteIceCream("The Tonight Dough")

Returning variables

Sometimes, we need to use a function to get a value. To do this, we just need to add a -> and then the data type we want. Below is an example of using this with addition.

func add(numOne: Int,  numTwo: Int) -> Int {
    return numOne+numTwo
}

var a = 2
var b = 3
var answer = add(numOne: 2, numTwo: 3)
print("When we add \(a) and \(b), we get \(answer)!")

As you can see, we returned the addition of numOne and numTwo. This was the value of answer.

One step further with booleans

Let’s take this one more step farther with returning booleans. The function below is used as a variable in the conditionals following it. This combines lots of what we have done in past lessons, so hopefully you understand this.

func isItSomeBlue(_ color: String) -> Bool {
    switch color {
        case "Red": { return false }
        case "Blue": { return true }
        case "Yellow": { return false }
        case "LightBlue": { return true }
        case Default: { return false }
    }
    return false // add this, otherwise Swift gets upset
}
    
if isItSomeBlue("Blue") {
    print("It's some color of blue!")
} else {
    print("It's not blueeee!")
}
    
if isItSomeBlue("Orange") {
    print("It's some color of blue!")
} else {
    print("It's not blueeee!")
}

Finished!

That was a very long section, but gives you an in depth look at how functions work in Swift. We will be using functions a lot, so make sure you know them!

chevron_up