- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
SWIFT
Swift inout: Syntax, Usage, and Practical Examples
The Swift inout
keyword allows functions to modify variables passed as parameters directly, rather than working on a copy of the variable. This makes inout Swift
a powerful feature for scenarios where a function needs to make changes to a variable that persist after the function call ends. In most cases, Swift function parameters are constants, meaning their values cannot be changed within the function. By marking a parameter with inout
, Swift treats the passed-in variable as mutable and allows those changes to reflect outside the function's scope.
What Is an inout Parameter in Swift?
An inout
parameter in Swift is a function parameter that can be modified inside the function and have those changes persist once the function completes execution. When a value is passed to an inout Swift
parameter, it is not passed by value like a normal parameter—it is passed by reference.
This allows the function to change the actual value of the variable provided by the caller, which can be useful for updating multiple values at once or for implementing low-level algorithms.
Example:
func increment(number: inout Int) {
number += 1
}
var value = 10
increment(number: &value)
print(value) // Output: 11
In this example, the &
symbol indicates that value
is being passed as an inout
parameter.
Syntax of Swift inout
Here is the general syntax for using inout
parameters:
func modify(parameter: inout Type) {
// Mutate parameter
}
var someVariable = initialValue
modify(parameter: &someVariable)
Important rules:
- You must use the
inout
keyword before the parameter's type. - When calling the function, you must use the
&
prefix to mark the variable as passed by reference.
This makes the behavior of Swift inout
clear both in the function definition and during function calls.
Multiple inout Parameters
You can define more than one inout
parameter in the same function. This is useful when you need to update multiple values together, such as swapping variables or adjusting related properties.
Example:
func swapValues(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 5
var y = 10
swapValues(&x, &y)
print(x, y) // Output: 10 5
In this example, Swift inout
enables the function to swap the values of x
and y
directly, without returning anything.
When to Use Swift inout
You should use inout Swift
parameters when:
- You want to modify a variable directly inside a function.
- The function doesn’t need to return a value but still affects external state.
- You are performing operations like sorting, swapping, accumulating values, etc.
However, it’s not a replacement for returning values. For most situations, prefer returning results unless modifying state is explicitly needed.
inout vs Return Value
Here’s a comparison of using inout
and returning a modified value:
Using return value:
func double(_ x: Int) -> Int {
return x * 2
}
let result = double(4)
Using inout
:
func double(_ x: inout Int) {
x *= 2
}
var num = 4
double(&num)
Both achieve the same goal, but inout
changes the original value directly. This style is typically reserved for cases where mutability is preferred or more efficient.
Restrictions and Considerations
While inout
is useful, it comes with some limitations and rules:
- Cannot be a constant: You cannot pass a constant, literal, or computed property to an
inout
parameter. - No default values: Parameters marked as
inout
cannot have default values. - Cannot be used with closures:
inout
parameters can’t be captured by escaping closures. - Mutability is required: The variable you pass must be declared as
var
, notlet
.
These constraints help ensure safety and prevent unexpected behaviors during execution.
inout in Swift: Practical Use Cases
Here are several real-world use cases where inout Swift
parameters are beneficial:
1. Swapping Two Variables
func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
This generic function uses inout
to allow type-safe swapping of any data type.
2. Cumulative Changes
func accumulate(value: Int, into total: inout Int) {
total += value
}
var total = 0
accumulate(value: 5, into: &total)
accumulate(value: 3, into: &total)
Useful in loops or while processing sequences.
3. Updating Struct Properties
In Swift, structs are value types. You can update a property by passing the whole struct as inout
:
struct Point {
var x: Int
var y: Int
}
func moveRight(_ point: inout Point, by distance: Int) {
point.x += distance
}
Alternatives to inout
Sometimes, using return values or reference types (like classes) is a better or simpler approach:
- Use return values when a single value needs modification.
- Use classes when you want shared mutable state.
- Use closures to defer execution with capture.
Reserve inout Swift
for cases where mutating state makes sense and enhances code clarity or performance.
Best Practices for Swift inout
To use inout
effectively:
- Avoid overusing it. In many cases, returning a value is more Swifty and functional.
- Document the behavior clearly, especially if side effects occur.
- Do not pass the same variable to multiple
inout
parameters in the same call—it may cause unexpected results. - Prefer meaningful function names that imply mutation.
Bad:
func change(_ a: inout Int) { a = 5 }
Better:
func resetToDefault(_ value: inout Int) {
value = 5
}
Summary
The Swift inout
keyword gives functions the ability to modify external variables directly. By enabling pass-by-reference behavior, inout
provides a way to create functions that change state without needing return values. It’s particularly helpful in algorithms that rely on variable mutation, such as sorting, accumulating totals, or modifying structs.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.