Open In App

Swift – Functions and its types

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A function in Swift is a standalone section of code that completes a particular job. Code is organized into functions that can be called repeatedly throughout a program to make it simpler to understand and maintain.

Here’s the basic syntax for defining a function in Swift:

Swift




func functionName(argument1: Type, argument2: Type, ...) -> ReturnType {
    // function body
    return returnValue
}


Parameters passed to functions:

  • func: keyword to define a function.
  • functionName: name of the function.
  • argument1, argument2: arguments passed to the function. Each argument consists of a name and a type.
  • ReturnType: the data type of the value returned by the function.
  • function body: the code that is executed when the function is called.
  • return: statement used to return a value from the function.

For example, here’s a simple function that takes two integer arguments and returns their sum:

Swift




func addNumbers(number1: Int, number2: Int) -> Int {
    let result = number1 + number2
    return result
}
 
//This function can be called like this:
let sum = addNumbers(number1: 5, number2: 7)
print(sum) // Output: 12


Swift functions can have multiple return values using tuples:

Swift




func calculateStatistics(numbers: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = numbers[0]
    var max = numbers[0]
    var sum = 0
 
    for number in numbers {
        if number < min {
            min = number
        } else if number > max {
            max = number
        }
        sum += number
    }
 
    return (min, max, sum)
}
 
//This function takes an array of integers as an argument and returns a tuple containing the minimum value, maximum value, and sum of the numbers.
let statistics = calculateStatistics(numbers: [5, 3, 10, 2, 7])
print(statistics.min) // Output: 2
print(statistics.max) // Output: 10
print(statistics.sum) // Output: 27


 

Types of Functions:

In Swift, there are several types of functions. Let’s take a look at each one:

1. Global Functions: These are functions that are defined outside of any class, structure or enumeration. Global functions can be called from anywhere within the program.

Swift




// Define a function that takes an array of integers as input and returns an integer as output
func calculateSum(_ numbers: [Int]) -> Int {
    // Create a variable to hold the sum of the numbers in the input array
    var sum = 0
     
    // Loop through each number in the input array
    for number in numbers {
        // Add the current number to the sum variable
        sum += number
    }
     
    // Return the sum of the input numbers
    return sum
}
 
// Create an array of numbers
let numbers = [1, 2, 3, 4, 5]
 
// Call the calculateSum function and pass in the numbers array as input
let sum = calculateSum(numbers)
 
// Print the output of the function
print(sum) // Output: 15


Output:

 

2. Nested Function: These are functions that are defined within another function. Nested functions can only be called from within the enclosing function.
 

Swift




// Define a function that takes two integers as input and returns an integer as output
func outerFunction(_ number1: Int, _ number2: Int) -> Int {
    // Define a nested function that takes an integer as input and returns an integer as output
    func innerFunction(_ number: Int) -> Int {
        // Multiply the input number by 2 and return the result
        return number * 2
    }
     
    // Call the innerFunction twice with the input numbers and add the results together
    let result1 = innerFunction(number1)
    let result2 = innerFunction(number2)
    return result1 + result2
}
 
// Define two input numbers
let number1 = 3
let number2 = 5
 
// Call the outerFunction with the input numbers
let result = outerFunction(number1, number2)
 
// Print the output of the function
print(result) // Output: 16


Output:

 

3. Methods: These functions are defined as part of a class, structure, or enumeration. Methods can access and modify the properties of that type.

Swift




// Define a class with a method that takes two integers as input and returns an integer as output
class Calculator {
    func addNumbers(_ number1: Int, _ number2: Int) -> Int {
        // Add the input numbers together and return the result
        return number1 + number2
    }
}
 
// Create an instance of the Calculator class
let calculator = Calculator()
 
// Call the addNumbers method on the calculator instance with two input numbers
let result = calculator.addNumbers(5, 7)
 
// Print the output of the method
print(result) // Output: 12


Output:

 

4. Closures: These are self-contained blocks of code that can be assigned to a variable or passed as an argument to a function.

Swift




// Define an array of numbers
let numbers = [1, 2, 3, 4, 5]
 
// Use the filter method to create a new array with only the even numbers from the input array
let filteredNumbers = numbers.filter { $0 % 2 == 0 }
 
// Print the output of the filter method
print(filteredNumbers) // Output: [2, 4]


Output:

 

5. Higher-order Functions: These are functions that take other functions as arguments or return functions as their result.

Swift




// Define a function that takes an array of integers and a closure as input and returns an array of integers as output
func filterIntegers(_ numbers: [Int], _ isIncluded: (Int) -> Bool) -> [Int] {
    // Create an empty array to hold the filtered integers
    var result = [Int]()
     
    // Loop through each number in the input array
    for number in numbers {
        // Call the closure on the current number to determine if it should be included in the output array
        if isIncluded(number) {
            // Add the current number to the output array if the closure returns true
            result.append(number)   
        }
}
 
// Return the filtered array of integers
return result
}
 
// Define an array of numbers
let numbers = [1, 2, 3, 4, 5]
 
// Define a closure that returns true for even numbers and false for odd numbers
let isEven: (Int) -> Bool = { $0 % 2 == 0 }
 
// Call the filterIntegers function with the input array and closure
let filteredNumbers = filterIntegers(numbers, isEven)
 
// Print the output of the function
print(filteredNumbers) // Output: [2, 4]


Output:

 



Similar Reads

Swift - Convert String to Int Swift
Swift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift provides String data type with the help of which we
3 min read
Swift - Properties and its Different Types
In Swift, properties are associated values that are stored in a class instance. OR we can say properties are the associate values with structure, class, or enumeration. There are two kinds of properties: stored properties and computed properties. Stored properties are properties that are stored in the class’s instance. Stored properties store const
13 min read
String Functions and Operators in Swift
A string is a sequence of characters that is either composed of a literal constant or the same kind of variable. For eg., "Hello World" is a string of characters. In Swift4, a string is Unicode correct and locale insensitive. We are allowed to perform various operations on the string like comparison, concatenation, iteration, and many more. We can
10 min read
Swift - Deinitialization and How its Works?
Deinitialization is the process to deallocate memory space that means when we finished our work with any memory then we will remove our pointer that is pointing to that memory so that the memory can be used for other purposes. In other words, it is the cycle to let loose unused space which was involved by unused class case objects for a better memo
4 min read
Higher-Order Functions in Swift
Higher-order functions are functions that take other functions as arguments or return functions as their output. These functions are an important aspect of functional programming, which is a programming paradigm that focuses on the use of functions to model computation. Higher-order functions enable developers to abstract common patterns of functio
10 min read
Calling Functions in Swift
Functions are independent lumps of code that play out a particular undertaking. You can give a name to the function that recognizes what it does, and also the name is utilized to "call" the function to play out its errand when required. Or we can say that a function is a bunch of orders/explanations. To make a straightforward function, you initiall
6 min read
Swift - Data Types
Data types are the most important part of any programming language. Just like other programming languages, in Swift also the variables are used to store data and what type of data is going to store in the variable is decided by their data types. As we know that variables are nothing but a reserved memory to store data so according to these data typ
5 min read
Swift - Difference Between Function and Method
Some folks use function and method interchangeably and they think function and method are the same in swift. But, function and method both are different things and both have their advantages. In the code, Both function and method can be used again but methods are one of these: classes, structs, and enums part, whereas functions do not belong to any
4 min read
Escaping and Non-Escaping Closures in Swift
In Swift, a closure is a self-contained block of code that can be passed to and called from a function. Closures can be passed as arguments to functions and can be stored as variables or constants. Closures can be either escaping or non-escaping. An escaping closure is a closure that is called after the function it was passed to returns. In other w
5 min read
Important Points to Know About Java and Swift
Java is a general-purpose, class-based, object-oriented programming language and computing platform which was first developed by Sun Micro System in the year 1995. It was developed by James Gosling. It was designed to build web and desktop applications and have lesser implementation dependencies. It is a computing platform for application developme
3 min read
Article Tags :