What is a function?

Going back to Chapter 1What is Programming?, you may remember that we defined programming as writing a set of instructions for a computer to execute. A function is a block of reusable code or instructions which generally performs a single specific task. A function abstracts one or more instructions and gives us a reference to that block of instructions. Chapter 4Favorite Things, showed us how to reference values using variables. In this chapter, you will learn that a function is basically a set of instructions or a chunk of code that is grouped together and referenced by a function name.

Let's imagine a real-world example for a moment. When you want to order a pizza, you call your local pizza joint. The people working at the pizza joint will then note down your order, put it into their queue of orders, make the pizza specified in your order and lastly, have it delivered to your address.

Actually, we can model these tasks as multiple functions:

  • A function to receive the order from the customer
  • A function to find the next order in the queue of orders
  • A function to make the actual pizza
  • A function to deliver the pizza to the customer

To help visualize what a function is, we can think of it as being a person performing a specific task-a person working at the pizza joint who writes down the order when we call them; a person who finds the next order in the queue; a person who takes the order and makes the pizza; and finally, a person who grabs the pizza and delivers it to you. We can think of a function being a person responsible for one specific task that we can ask the person to perform. We might need to give the person some information related to the task, for example, the pizza we want to order, and the person might return something after the task has been performed, for example, the pizza.

This series of work performed at the pizza joint-taking the order, putting it into the order queue, and finally, making the pizza-has some shared characteristics with a function in a programming language, such as Swift.

A function can receive some input

When we want to order a pizza at our local pizza joint, we usually call the place and let them know what pizza on the menu we want to order. If we imagine the person working at the pizza joint to be our function, we could say that the pizza we want to order is the input for that function. If the pizza joint is expecting multiple input, for example, my order and my phone number, the order of which I provide the input is important. We can generally think of input as being the information needed to perform the task the function is responsible for. Similarly, one can think of devices such as a keyboard, mouse, trackpad, and more being input for a computer:

A function can receive some input

These devices help us communicate with our computer in terms of input which the computer can process and then, for example, display it on a computer monitor.

A function can be pure

A function can be self-contained (or pure), which means that all the requirements needed in order for a function to perform its task are provided to the function. If we take a look at the arithmetic operation of addition, that is, adding two numbers together, for example, 2 + 3 = 5, we can consider this operation as a function. The function takes in two or more input values, in this case the values 2 and 3, and it returns the result of the operation, in this case 5. When moving a shipping container around the world, the container is filled with the goods it is supposed to carry and then locked. The container does not magically get more goods after being locked and made ready for transportation. Its function to carry goods is literally self-contained.

A function can be pure

Going back to our pizza example, we can say that in order for the pizza joint to process our order, they obviously need some input. They need to know what pizza we want and we can inform them using a name or number from their menu. We don't call the pizza joint saying that we want a pizza and then hang up, expecting that they will call us back for more information when they start making the pizza. In this case, we could say that the task of making our pizza is self-contained because all the information needed in order to make the pizza is given upfront before performing the task.

A function can return something

When we ask a person to perform a task, there might be a result that is being returned to us after the task has been performed. In our pizza example, we can consider the actual pizza being the result of the pizza joint or the chef performing the task of making our pizza. In the example, with the arithmetic operation, the result of adding 2 and 3 is the result or the return value of that task. A person delivering ordered goods is like a function returning a value to its caller:

A function can return something

There might be cases where a function or task does not return anything. It might be that we're not interested in the result, but it could also be the case where the task does not generate any result at all. Let's revisit some of the code we created together in Chapter 3Say Hello:

print("Hello World")

As we learned in Chapter 3, Say Hello, this simple piece of code does nothing other than print Hello World to the console. What if we abstracted this work of printing the sentence, which means that we would be able to call a function that takes care of printing the sentence to the console. What would the return value be? The sentence itself or maybe nothing? Sometimes it does not make sense to return a value, and having a function that only prints to the console is a reasonable example. We can refer to these functions as fire and forget functions as we call them, but without knowing what happens next, in the sense that we don't get a response indicating whether they succeeded or not.

A look at functions in Swift

We've been covering some of the different characteristics of functions that are shared among different programming languages. Next, let's focus on what functions in Swift look like.

Let's start by creating the function that simply prints Hello World to the console. This function does not take any input values and it will not return any value:

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

We declare a function using the func keyword. This is how Swift has defined what a function looks like and this ensures that our iPhone will know that this is a function. The next part is the name of our function, in this case sayHello. In Swift, we define our function names using a strategy, called camel case. It is a simple pattern where we write names with no spaces or hyphens but capitalize each word or abbreviation in the middle of the phrase. Camel case can start with a capital letter or a lowercase letter. In Swift, we use a lowercase letter for the first word in our methods. The next part of our function is the parentheses-(). The parentheses contains the input values for our function. If we're not interested in any input values, we omit them by making the parentheses empty, as in our current example. The last part is our function body, which is indicated by our curly braces-{}. The code we place inside our function body will be executed when we call our function. We say that we call or invoke our function when referencing the function name with zero or many input values. Input values are usually referred to as parameters and we say that a function takes x parameters. Parameters are usually denoted by a label, which are basically variables for the function. This means that when we call a function with some values, these values are assigned to the variables (or labels) of the function. This is convenient as we can then access these values inside the function body.

Before creating our own function and looking at how we can call them, let's take a quick look at a couple of examples of what functions look like in Swift. The following one takes in a parameter that is the text and it has to be of the String type. The function doesn't return any value and all it does is to print the specified text value to the console:

func printToConsole(text: String) {
   print(text)
}

The next function takes in two parameters: firstName and lastName. This function returns a value, as indicated by -> (and the return statement inside the function body) and the type of the return value is String. The function body creates a string using the specified firstName and lastName and returns it:

func fullName(firstName: String, lastName: String) -> String {
   let fullName = "(firstName) (lastName)"
   return fullName
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.143