Arrays
Overview
Arrays are one of the most fundamental and widely used data structures in any programming language, including Swift. They allow you to store an ordered collection of elements—such as integers, strings, or custom objects—and access them efficiently by index.
In Swift, arrays are implemented as generic value types and provide a robust, flexible API for collection operations.
Why Use Arrays?
Arrays are ideal when:
You need ordered access to data.
Index-based lookup is required.
You want to iterate over elements in sequence.
You frequently append or retrieve values at the end.
Declaring Arrays
Swift arrays are strongly typed. You can either infer or explicitly declare the type.
// Type inference
var numbers = [1, 2, 3, 4]
// Explicit type declaration
var names: [String] = ["Alice", "Bob", "Charlie"]
// Empty array
var scores: [Int] = []
Common Operations
Accessing Elements
let first = numbers[0] // 1
Adding Elements
numbers.append(5)
numbers += [6, 7]
Inserting Elements
numbers.insert(0, at: 0)
Removing Elements
numbers.remove(at: 0)
numbers.removeLast()
numbers.removeAll()
Iterating
for number in numbers {
print(number)
}
Or with indices:
for (index, value) in numbers.enumerated() {
print("Index \(index): \(value)")
}
Performance Characteristics
Operation |
Time Complexity |
---|---|
Access by index |
O(1) |
Append |
Amortized O(1) |
Insert at start |
O(n) |
Remove from end |
O(1) |
Remove from middle |
O(n) |
Search (unsorted) |
O(n) |
Swift arrays are backed by a contiguous memory buffer, making access and append operations fast. But inserting or removing elements at arbitrary positions can be costly.
Value Semantics and Copy-on-Write
Arrays in Swift are value types, meaning they’re copied when assigned or passed. However, Swift uses copy-on-write to avoid unnecessary duplication:
var a = [1, 2, 3]
var b = a
b.append(4) // Now `a` and `b` are different
Until b
is mutated, both variables share the same storage.
Useful Built-in Methods
numbers.contains(3)
numbers.first
numbers.last
numbers.sorted()
numbers.filter { $0 % 2 == 0 }
numbers.map { $0 * 2 }
Array Slicing
Swift allows you to work with subranges:
let slice = numbers[1...3] // ArraySlice<Int>
To get an actual array:
let subarray = Array(slice)
When Not to Use Arrays
Arrays are not ideal when:
You need constant-time insertion/deletion at both ends. Use
Deque
orLinkedList
.You need fast search. Use a
Set
orDictionary
instead.
Custom Algorithms on Arrays
Let’s implement a few basic algorithms using arrays in Swift.
1. Linear Search
func linearSearch<T: Equatable>(_ array: [T], key: T) -> Int? {
for (index, value) in array.enumerated() {
if value == key {
return index
}
}
return nil
}
2. Reverse Array
func reverse<T>(_ array: [T]) -> [T] {
var result = array
var left = 0
var right = result.count - 1
while left < right {
result.swapAt(left, right)
left += 1
right -= 1
}
return result
}
3. Remove Duplicates
func removeDuplicates<T: Hashable>(_ array: [T]) -> [T] {
var seen: Set<T> = []
return array.filter { seen.insert($0).inserted }
}
Advanced Topics
Arrays of Custom Types
You can store any type, including custom structs and classes.
struct Person {
let name: String
let age: Int
}
let people: [Person] = [
Person(name: "Alice", age: 28),
Person(name: "Bob", age: 32)
]
Multi-Dimensional Arrays
Swift does not have built-in 2D arrays, but you can use arrays of arrays:
let matrix: [[Int]] = [
[1, 2, 3],
[4, 5, 6]
]
Accessing an element:
let item = matrix[1][2] // 6
Best Practices
Prefer
let
overvar
unless mutation is required.Avoid using force unwraps or unsafe indexing.
Use high-order functions like
map
,filter
, andreduce
for expressiveness.Consider using
Set
when uniqueness is required.
Conclusion
Arrays are an essential building block in Swift. They provide fast, reliable, and expressive ways to work with ordered data. Understanding their behavior, especially around performance and copy-on-write semantics, is critical for writing efficient and safe Swift code.
In the next chapter, we’ll explore Linked Lists, which offer more flexibility in insertion and deletion, especially in large-scale or memory-sensitive contexts.