Swift Functions with Examples

Placement-ready Courses: Enroll Now, Thank us Later!

Functions are reusable blocks of code in a program. It performs a specific task like addition or printing or even some other complex task. It might take parameters, and it might also return values. It makes our code more modular. In this article, we’ll learn about the basics of functions, functions with or without parameters and return values, their different types and their usage in programming in Swift.

Kinds of Functions in Swift

There are two main kinds of functions. They can be standard library functions, or they can be user-defined functions.

Library Functions

Swift offers inbuilt functions for our use. These are known as standard library functions.

Some of the common library functions are print(), pow(), etc.

These can directly be used in our programs. These library functions are included in frameworks, so we need to import the framework corresponding to it.

For example, pow() is defined in the Foundation Framework of Swift.

User-defined Functions

Users define their own functions. These are known as user-defined functions. These kinds of functions are discussed in detail below.

Function Declaration in Swift

We use the func keyword followed by the name of the function to define a function. We mention the parameters of the function within parentheses (). We can optionally specify the return type after parentheses. The body of the function is written within braces {}. We write the return statement at the end of the body of the function.

The syntax of a function.

func functionName(parameter1, parameter2, ..., parameterN) -> returnType{
    //Function Body
    Return statement
}

For example, we have to define a function that multiplies 2 numbers.

Parts of the functionName of the component in the function
Name of the functionmultiply
Parametersnum1, num2
Return TypeInt
func multiply(num1: Int, num2: Int) -> Int{
    let temp = num1 * num2
    return temp
}

Calling a function

We call a function by writing the function name followed by writing the parameters (if they are defined).

func multiply(num1: Int, num2: Int) -> Int{
    let temp = num1 * num2
    return temp
}

var product = multiply(num1: 4, num2: 5)
print("Product: \(product)")

Output:

Product: 20

Function, Parameters and Return Values

A function might take a parameter. It might have a return value. It can also have an optional return value. It can also have an implicit return value. Based on a specific scenario and use case, we might have a parameter or return value. Below, we have discussed each of these with examples.

Function with Parameters

Functions with parameters are functions that contain one or more parameters in their argument.

For example,

func greetName(name:String){
    print("Hello from \(name)!")
}

greetName(name: "DataFlair")

Output:

Hello from DataFlair!

Function without Parameters

Functions can also be defined without parameters. For example,

func greet(){
    print("Hello from DataFlair!")
}

greet()

Output:

Hello from DataFlair!

Function with Return Values

Functions with return values usually return one or more values after completion of the task. We need to specify the return type of the function. We write an arrow symbol -> after the parentheses followed by the return type. We can refer to the following syntax to understand it better.

func functionName() -> ReturnType{
    //body
    Return value
}

Example for the same.

func addNums(num1: Int, num2: Int) -> Int{
    return num1 + num2
}

let sum = addNums(num1: 20, num2: 23)
print("Sum is \(sum)")

Output:

Sum is 43

Function without Return Values

A function can also be written without return values. These functions return a special type known as void type. For example,

func greet(){
    print("Hello from DataFlair!")
}

greet()

Output:

Hello from DataFlair!

Function with Optional Return Values

When we are not sure whether we will get a result or not, we can use optional return values. We can define these by adding a question mark ‘?’ after the return type of the function. If there is no value to return, nil is returned.

func findDataFlair(sentence: String) -> String?{
    if sentence.contains("DataFlair"){
        return "DataFlair"
    }else{
        return nil
    }
}
let exampleSentence = "Hello from DataFlair"

if let example = findDataFlair(sentence: exampleSentence){
    print("\(example) found.")
}else{
    print("Not found.")
}

Output:

DataFlair found.

Function with Implicit Return Values

In some functions, we don’t need to explicitly write the return statement in the function declaration. The whole body of the function can be returned in a single expression. For example,

func greet() -> String{
    "Hello from DataFlair!"
}

let example: String = greet()
print(example)

Output:

Hello from DataFlair!

More on Swift Function Parameters

Swift offers several uses of parameters. They can be used in several ways. We can use this based on our use case and convenience. Some of these are argument labels, local and external parameter names, variadic parameters and InOut parameters.

Local Parameter Names and External Parameter Names

We use local parameter names inside the function body locally. It is also known as internal parameter names.

func greet(name: String){
    //name is an internal parameter
    print("Hello from \(name)!")
}

We use external parameter names while calling the function externally. It is also known as argument labels.

func greet(name: String){
    //name is an internal parameter
    print("Hello from \(name)!")
}

//name is an external parameter here
greet(name: "DataFlair")

Output:

Hello from DataFlair!

Argument Labels are explained in detail in the next subtopic.

Argument Labels

Argument Labels are descriptive names of function parameters. We write them in the function signature when we call them externally.

An example of argument labels is as follows

func greet(fromPerson name: String){
    print("Hello from \(name)!")
}

greet(fromPerson: "DataFlair")

Output:

Hello from DataFlair!

We can also omit these argument labels while calling the function. We can do it by writing an underscore ‘_’ instead of a label while defining the function. For example,

func greet(_ name: String){
    print("Hello from \(name)!")
}

greet("DataFlair")

Output:

Hello from DataFlair!

Variadic Parameters

We can define a function with multiple parameters with the help of variadic parameters. We do it by adding an ellipsis (…) after the parameter name. For example,

func sum(numbers: Int...)->Int{
    var total = 0
    for number in numbers{
        total += number
    }
    return total
}

print(sum(numbers: 2, 5, 7, 9, 10))

Output:

33

InOut Parameters

Inout parameters change the value of the variable passed through a function. To declare an inout parameter, we write the inout keyword before the data type. The variable needs to be mutable.

We call a function with inout parameters by prefixing the variables with an ampersand ‘&’. This means that we want to pass them by reference. This allows the function to modify its value.

func swapValues(_ num1: inout Int, _ num2: inout Int){
    let temp = num1
    num1 = num2
    num2 = temp
}

var num1 = 6
var num2 = 10

print("Before Swapping \(num1), \(num2)")
swapValues(&num1, &num2)
print("After Swapping \(num1), \(num2)")

Output:

Before Swapping 6, 10
After Swapping 10, 6

Function Types

We can convert functions into data types. We can treat them as regular data types. We can assign them to variables. We can pass them as arguments in other functions. We can also return them from other functions.

func greet(name: String){
    print("Hello from \(name)")
}
let printGreetings: (String) -> Void = greet

printGreetings("DataFlair")

Output:

Hello from DataFlair

Nested Functions

Functions defined inside another function are known as nested functions. The syntax of nested functions is as follows.

func functionName1(){
    //func body
    func functionName2(){
        //func body
    }
}

The example below defines the inner and outer functions.

func function1(){
    print("Outer Function")
    func function2(){
        print("Inner Function")
    }
    
    function2()
}
function1()

Output:

Outer Function
Inner Function

We cannot call the inner function outside of the outer function. It throws errors if we can an inner function from outside of the outer function.

Conclusion

Functions help us in reusing our code. They make our code modular. In this article, we have discussed about kinds of Swift functions and how we use them. We have seen how to declare and use these functions based on our requirements. We’ve learnt about different combinations of functions with and without parameters and return values. We have also gone through different kinds of parameters defined in Swift.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *