0
0
Swiftprogramming~5 mins

Closures are reference types in Swift

Choose your learning style9 modes available
Introduction

Closures let you store blocks of code that can be used later. Knowing they are reference types helps you understand how they behave when copied or passed around.

When you want to pass a piece of code to a function to run later.
When you want to keep a function with some saved data inside it.
When you want multiple parts of your program to share the same block of code and its data.
When you want to avoid copying big chunks of code and just share one copy.
Syntax
Swift
let closureName = { (parameters) -> ReturnType in
    // code here
}
Closures can capture and store references to variables from the surrounding context.
Because closures are reference types, when you assign or pass them, you share the same closure instance.
Examples
A simple closure that prints a greeting.
Swift
let greet = { print("Hello") }
greet()
This closure changes a variable outside its own code. It captures count by reference.
Swift
var count = 0
let increment = { count += 1 }
increment()
print(count)
Both closure1 and closure2 point to the same closure because closures are reference types.
Swift
let closure1 = { print("Hi") }
let closure2 = closure1
closure2()
Sample Program

This program shows that addFive and anotherAddFive are references to the same closure. Calling either changes the same value.

Swift
var value = 10
let addFive = { value += 5 }
let anotherAddFive = addFive
addFive()
print(value)  // prints 15
anotherAddFive()
print(value)  // prints 20
OutputSuccess
Important Notes

Because closures are reference types, changing a closure through one variable affects all references to it.

Be careful with closures capturing variables to avoid unexpected changes.

Summary

Closures store blocks of code and can capture variables from around them.

Closures are reference types, so copying them shares the same instance.

This means changes inside one closure reference affect all others pointing to it.