Swift – Functions and its types
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: