Understanding Functions and Closures in Swift Programming
Written on
Key Insights on Functions in Swift
In Swift, functions are foundational elements used to execute tasks involving data. They help organize your code into manageable, reusable segments. For example:
func sayHello() {
print("Hello")
}
sayHello() // Outputs "Hello"
Functions can also return values to the calling code, indicated by the arrow (->) syntax:
func usefulNumber() -> Int {
return 123
}
let aUsefulNumber = usefulNumber() // 123
Parameters can be passed to functions within parentheses, enabling them to perform operations:
func addNumbers(firstValue: Int, secondValue: Int) -> Int {
return firstValue + secondValue
}
let outcome = addNumbers(firstValue: 1, secondValue: 2) // 3
Functions are capable of returning a single value or multiple values in a tuple. When a function returns a tuple, you can access its values either by index or by name:
func processNumbers(firstValue: Int, secondValue: Int) -> (doubled: Int, quadrupled: Int) {
return (firstValue * 2, secondValue * 4)
}
// Accessing by index:
processNumbers(firstValue: 2, secondValue: 4).1 // = 8
// Accessing by name:
processNumbers(firstValue: 2, secondValue: 4).quadrupled // = 8
Function Parameter Labels
By default, all parameters following the first one require a label when calling the function. However, you can omit the label by placing an underscore before the parameter names:
func subtractNumbers(_ num1: Int, _ num2: Int) -> Int {
return num1 - num2
}
subtractNumbers(5, 3) // 2
You can also assign custom labels to parameters:
func add(firstNumber num1: Int, toSecondNumber num2: Int) -> Int {
return num1 + num2
}
add(firstNumber: 2, toSecondNumber: 3) // 5
Default and Variadic Parameters
Functions can have parameters with default values, which allows you to call them without specifying certain arguments:
func multiplyNumbers(firstNumber: Int, multiplier: Int = 2) -> Int {
return firstNumber * multiplier
}
// Default value used
multiplyNumbers(firstNumber: 2) // 4
For functions requiring a variable number of arguments, use variadic parameters denoted by three dots (...):
func sumNumbers(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number}
return total
}
sumNumbers(numbers: 1, 2, 3, 4, 5) // 15
Passing Parameters by Reference
Typically, function parameters and return values are passed by value. However, using the inout keyword allows you to pass parameters by reference:
func swapValues(firstValue: inout Int, secondValue: inout Int) {
(firstValue, secondValue) = (secondValue, firstValue)
}
var swap1 = 2
var swap2 = 3
swapValues(firstValue: &swap1, secondValue: &swap2)
swap1 // 3
swap2 // 2
Storing and Using Functions
You can assign functions to variables:
var numbersFunc: (Int, Int) -> Int
numbersFunc = addNumbers
numbersFunc(2, 3) // 5
Functions can also accept other functions as parameters:
func timesThree(number: Int) -> Int {
return number * 3
}
func doSomethingWith(aNumber: Int, action: (Int) -> Int) -> Int {
return action(aNumber)
}
doSomethingWith(aNumber: 4, action: timesThree) // 12
Returning Functions
Functions can return other functions:
func createAdder(numberToAdd: Int) -> (Int) -> Int {
func adder(number: Int) -> Int {
return number + numberToAdd}
return adder
}
var addTwo = createAdder(numberToAdd: 2)
addTwo(2) // 4
Understanding Closures
Closures are compact, anonymous code segments that function similarly to methods. They're particularly useful for passing to other functions to dictate how tasks should be executed. For instance:
let jumbledArray = [2, 5, 98, 2, 13]
jumbledArray.sorted() // [2, 2, 5, 13, 98]
let numbers = [2, 1, 56, 32, 120, 13]
let numbersSorted = numbers.sorted(by: { (n1: Int, n2: Int) -> Bool in return n2 > n1 })
Explore more about closures, including expression syntax and types, in the following resources.
This video titled "Swift Closures Explained" offers a comprehensive overview of closures in Swift, detailing their syntax and practical applications.
Check out "Swift Closures Explained - The ONLY video you'll ever need!" for an in-depth look at closures and how to leverage them effectively in your Swift projects.
Thank you for reading! If you found this article helpful, please share it and give some claps so others can discover it too! 🎉