Swift - Functions and its types
Last Updated :
28 Apr, 2025
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
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
6 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 t
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
10 min read
Swift Function Parameters and Return Values A function is a piece of code that is used to perform some specific task. Just like other programming languages Swift also has functions and the function has its name, parameter list, and return value. Their syntax is flexible enough to create simple as well as complex functions. All the functions i
10 min read
Swift - Constants, Variables & Print function Constants and variables are those elements in a code linked with a particular type of value such as a number, a character, a string, etc. Constants once declared in a code cannot be changed. In comparison, variables can change at any time in a code within the scope.Declaring Constants & Variable
2 min read
Swift - Nested Function A function is a collection of statements grouped together as a block to perform a specific task. The return type of a function decides the type of value returned by the function. For example, if we want to get an integer value from a function then the return type of the function must be Int, if we w
5 min read