English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Functions (func)

In this article, you will learn about functions in Swift, what functions are, syntax, and types through examples.

What is a function?

A function is a set of statements that define actions to be executed. The main purpose of a function is to make code reusable.

In terms of technology, you can view functions as machines. Machines perform specific tasks, requiring input, processing input, and returning output.

Function types

Depending on whether the function is predefined or created by the programmer; functions have two types:

  1. Library functions - Functions already defined in the Swift Framework.

  2. User-defined functions - Functions created by programmers themselves.

Library functions

Library functions are built-in functions already defined in the Swift framework. These functions are provided to solve common problems in Swift, so you do not have to solve them yourself. They are simple operations, such as printing, finding the minimum and maximum values, etc.

You can use the library function directly by calling it. If you need, you can see all the functions within the Swift framework. Just write import Swift, press Cmd, and click it. You will navigate to a new page. Search for all statements that start with the func keyword.

Example1: Libraries or built-in functions

print("Hello, World!")

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

Hello, World!

In the above program, we called the built-in function print defined in the Swift framework. This function is used to print output to the console.

We can call the print() function because the Swift framework is automatically imported into our Playground. Otherwise, we should import it ourselves by using import Swift.

User-defined functions

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

Similarly, functions can also be classified according to parameters and return statements. Refer to the articleSwift Function Parameter and Return Types.

Define function

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

Let's briefly explain the components of a function:

  • func Is the keyword that must be written to create a function

  • function_name Is the name of the function. You can give it any name that defines the function's functionality.

  • args… Defines the input accepted by the function.

  • -> This operator is used to indicate the return type of the function.

  • ReturnType defines the type of value that can be returned from the function. For example, Int, String, etc.

  • The return keyword is used to transfer control of the program to the function call and return the value from the function.
    Even if you do not specify return Keywords, the function will also automatically return after executing the last statement.

  • value represents the actual data returned from the function. The value type must match ReturnType.

How does the function work?

In the figure above, the statement function_name(args) calls the parameter value args./Call the function, then leave the current part of the code (i.e., stop executing the statements below) and start executing the first line inside the function.

  1. The first line of the program, func function_name(Args...), accepts the values args passed during the function call function_name(args).

  2. Then the program executes the statementsInsideFunction statements defined inside the function.

  3. The statements inside the function are executed one by one in the order from top to bottom.

  4. After executing the last statement, the program leaves the function and returns to the place where it started Function_Name(Args).

  5. let val = stores the value returned by the function as a constant val. Similarly, you can store a variable as var val =.

  6. After that, the statementsOutsideFunction statements will be executed.

Example2: How to define a function in Swift?

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

The following is a function definition that includes the following components:

  1. The keyword func marks the beginning of the function header.

  2. greet is the function name used to uniquely identify and call the function in the program.

  3. Parameter and return types of Swift functions, they define functions with parameters.

  4. The function consists of a single print statement that is executed after the function is called.

Function call

Once a function is created, it can be called in the program to execute the statements declared in the function. To call a function, you just need to write the function name followed by() and pass the input parameters to it:

greet(user: "Isac")

Example3: 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, the custom function greet(user: "Isac") is called and a string value Isact is passed. After that, print executes the statements inside the function.

Return statement

The return keyword tells the program to exit the function and return to the line where the function was called.

You can also use the return keyword to pass a value, where value is a variable or other information returned from the function.

Example3: Function with return keyword

func greet(user: String)-> String {
    return "Good Morning! \(user)"
}
let greeting = greet(user: "Isac")
print("""
     You have a new message
     \(greeting)
     ""

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

You have a new message
Good Morning! Isac

In the above code, the custom function greet(user: "Isac") is called and a string value Isact is passed. The statement return "Good Morning! \(user)" returns a String value and transfers the program to the function call.

let greeting = store the value returned from the function. After the function returns, the print statement below the function call will be executed.

Considerations for Function Usage

  • Specify a function name that reflects the function's purpose.

  • A function should perform only one task. If a function performs multiple tasks, break it down into multiple functions.

  • Try to think and organize statements as early as possible in a function to make the code reusable and modular.