Module 4: Functions and Closures in Swift
Functions are reusable blocks of code that perform specific tasks. In Swift, functions help organize your code into logical sections, making it easier to read, debug, and maintain.
Defining a Function
Here’s the basic syntax to define a function in Swift:
func greet() {
print("Hello, Swift learner!")
}
This function named greet
takes no parameters and simply prints a message.
Calling a Function
To execute a function, call it by its name followed by parentheses:
greet()
// Output: Hello, Swift learner!
Functions with Parameters and Return Values
Functions can accept inputs (parameters) and return a value.
Example: Function with Parameter
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "John")
// Output: Hello, John!
Example: Function with Return Value
func square(number: Int) -> Int {
return number * number
}
let result = square(number: 5)
print(result) // Output: 25
Functions with Multiple Parameters
func add(a: Int, b: Int) -> Int {
return a + b
}
print(add(a: 3, b: 7)) // Output: 10
Default Parameter Values
You can provide default values for parameters so callers can omit them.
func greet(name: String = "Guest") {
print("Welcome, \(name)!")
}
greet() // Output: Welcome, Guest!
greet(name: "Amy") // Output: Welcome, Amy!
Variadic Parameters
Functions can accept zero or more values of the same type.
func sum(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
print(sum(numbers: 1, 2, 3, 4)) // Output: 10
Nested Functions
Swift allows defining functions inside other functions.
func outerFunction() {
func innerFunction() {
print("Inner function called")
}
innerFunction()
}
outerFunction()
// Output: Inner function called
What Are Closures?
Closures are self-contained blocks of functionality that can be passed around and used in your code. They are similar to anonymous functions or lambdas in other languages.
Basic Closure Syntax
let sayHello = {
print("Hello from closure!")
}
sayHello()
// Output: Hello from closure!
Closures with Parameters and Return Values
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
print(multiply(4, 5)) // Output: 20
Using Closures as Function Parameters
Closures are often used as callbacks or completion handlers.
func performOperation(_ operation: (Int, Int) -> Int, a: Int, b: Int) {
let result = operation(a, b)
print("Result: \(result)")
}
performOperation({ $0 + $1 }, a: 10, b: 20) // Output: Result: 30
Shorthand Closure Syntax
performOperation({ $0 * $1 }, a: 3, b: 7) // Output: Result: 21
Summary
- Functions are reusable code blocks defined with
func
. - Functions can take parameters and return values.
- Parameters can have default values or accept multiple arguments (variadic).
- Closures are anonymous functions that can be stored in variables or passed around.
- Closures can simplify callbacks and functional programming patterns.