Swift Functions

In this article, you'll learn everything about functions, what is a function, syntax, types in Swift with examples.

What is a function?

A function is a group of statements that defines an action to be performed. The main use of a function is to make the code reusable.

Non technically, you can think of a function as a machine. A machine performs a specific task, asks for input, processes the input and returns the output.

Types of Functions

Depending on whether a function is predefined or created by programmer; there are two types of function:

  1. Library functions - Functions that are defined already in Swift Framework.
  2. User-defined functions - Functions created by the programmer themselves.

Library Functions

Library functions are built-in functions that are already defined in Swift framework. These functions are present to solve common problems in Swift so that you don't have to solve them yourselves. They are simple operations like printing, finding minimum and maximum, etc.

You can use library function directly by invoking (calling) it. If you want, you can see all the functions inside the Swift framework. Just write import Swift, press Cmd and Click it. You will navigate to a new page. Search all the statements starting with func keyword.

Example 1: Library or Built in Function

print("Hello, World!")

When you run the above program, the output will be:

Hello, World!

In the above program, we have invoked a built-in print function defined in Swift Framework. The function is used to print output in the console.

We are able to call print() function because Swift framework is automatically imported into our Playground. Otherwise, we should have imported it ourselves by writing import Swift.

User defined Functions

Swift also allows you to define your own function. Creating your own function helps to write code to solve problems or perform tasks not available in Swift Framework. You can also reuse your function to perform similar tasks in the future.

Likewise, Functions can also be categorized in the basis of parameters and return statements. See the article Swift Function Parameter Types and Return Types.

Defining a Function

func function_name(args...) -> ReturnType {
    return value

Lets describe each components in brief:

  • func is the keyword you must write to create a function
  • function_name is the name of a function. You can give it any name that defines what a function does.
  • args… defines the input a function accepts.
  • -> This operator is used to indicate the return type of a function.
  • ReturnType defines the type of a value you can return from a function. E.g. Int, String etc.
  • return keyword is used to transfer the control of a program to the function call and also return value from a function.
    Even if you don’t specify the return keyword the function returns automatically after execution of last statement.
  • value represents the actual data being returned from the function. The value type must match the ReturnType.

How function works?

How function works in Swift?

In the above diagram, the statement function_name(args) invokes/calls the function with argument values args, which then leaves the current section of code (i.e. stops executing statements below it) and begins to execute the first line inside the function.

  1. The program comes to a line of code func function_name(Args...) and accepts the values args passed during the function call function_name(args).
  2. The program then executes the statements statementsInsideFunction defined inside the function.
  3. The statements inside the function are executed in top to bottom order, one after the other.
  4. After the execution of the last statement, the program leaves the function and goes back to where it started from i.e function_name(args).
  5. let val = stores the value returned from the function in a constant val. Similarly, you can store in a variable as var val =.
  6. After that, statements statementsOutsideFunction are executed.

Example 2: How to define a function in Swift?

func greet(user:String) {
    print("Good Morning! \(user)")

Above shown is a function definition which consists of following components:

  1. Keyword func marks the start of function header.
  2. greetis a function name to uniquely identify and call function in the program.
  3. (user:String) marks the end of function header and accepts a parameter of type String. See the article Swift Function Parameter Types and Return Types that defines function with parameters.
  4. The function consists of a print statement inside the body which executes after you call the function.

Calling a function

Once you have created a function, you can call it in your program to execute the statements declared inside the function. To call a function you simply write the function name followed by ()and pass the input parameters inside it as:

greet(user: "Isac")

Example 3: Calling a function in Swift

func greet(user:String) {
    print("Good Morning! \(user)")

greet(user: "Isac")

When you run the above program, the output will be:

Good Morning! Isac

In the above code, greet(user: "Isac") calls the function and passes valueIsac of type String. After that, print statement inside the function executes.

Return Statement

The return keyword tells the program to leave the function and return to line where the function call was made.

You can also pass value with the return keyword where value is a variable or other information coming back from the function.

Example 3: Function with return keyword

func greet(user:String)-> String {
    return "Good Morning! \(user)"

let greeting = greet(user: "Isac")
     You have a new message

When you run the above program, the output will be:

You have a new message
Good Morning! Isac

In the above code, greet(user: "Isac") calls the function and passes value Isac of type String. return "Good Morning! \(user)" statement returns the value of type String and transfers the program to the function call.

let greeting = stores the value returned from the function. After the function returns, the print statement below the function call executes.

Things to remember

  • Give a function name that reflects the purpose of the function.
  • A function should accomplish only one task. If a function does more than one task, break down it into multiple functions.
  • Try to think early and group statements inside a function which makes the code reusable and modular.