- Published on
- 4 min read
> All the Ways to Add Elements to an Array in Swift
Arrays are the workhorse collection type in Swift, and adding elements to them is something you'll do constantly. Swift provides several methods depending on whether you're adding one element or many, and whether position matters.
Adding a Single Element with append()
The most common way to add an element is append(), which adds to the end of the array:
var fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) // ["apple", "banana", "cherry"]
This mutates the array in place and runs in O(1) amortized time. Swift arrays automatically resize when needed, so individual appends are fast.
Adding Multiple Elements with append(contentsOf:)
When you have a sequence of elements to add, use append(contentsOf:) instead of looping with append():
var numbers = [1, 2, 3]
numbers.append(contentsOf: [4, 5, 6])
print(numbers) // [1, 2, 3, 4, 5, 6]
This works with any Sequence, not just arrays:
var letters = ["a", "b"]
letters.append(contentsOf: "cde") // String is a Sequence of Characters
print(letters) // ["a", "b", "c", "d", "e"]
var moreNumbers = [1, 2]
moreNumbers.append(contentsOf: 3...7)
print(moreNumbers) // [1, 2, 3, 4, 5, 6, 7]
Inserting at a Specific Position
When you need to add an element somewhere other than the end, use insert(_:at:):
var colors = ["red", "blue"]
colors.insert("green", at: 1)
print(colors) // ["red", "green", "blue"]
The index must be valid: from 0 up to and including the array's count. Inserting at index count is equivalent to appending:
var items = ["first"]
items.insert("second", at: 1) // Same as append
print(items) // ["first", "second"]
For inserting multiple elements at once, use insert(contentsOf:at:):
var alphabet = ["a", "d", "e"]
alphabet.insert(contentsOf: ["b", "c"], at: 1)
print(alphabet) // ["a", "b", "c", "d", "e"]
Keep in mind that inserting at the beginning or middle requires shifting existing elements, making it O(n) rather than O(1).
Concatenation with + and +=
Swift lets you combine arrays with the + operator, which creates a new array:
let first = [1, 2, 3]
let second = [4, 5, 6]
let combined = first + second
print(combined) // [1, 2, 3, 4, 5, 6]
The original arrays remain unchanged. If you want to modify an array in place, use +=:
var numbers = [1, 2, 3]
numbers += [4, 5]
print(numbers) // [1, 2, 3, 4, 5]
The += operator is essentially shorthand for append(contentsOf:), so numbers += [4, 5] and numbers.append(contentsOf: [4, 5]) do the same thing.
Replacing a Range with replaceSubrange()
While not strictly "adding," replaceSubrange(_:with:) lets you replace a section of an array with a different number of elements:
var letters = ["a", "b", "c", "d", "e"]
letters.replaceSubrange(1...3, with: ["x", "y"])
print(letters) // ["a", "x", "y", "e"]
You can use this to insert elements by replacing an empty range:
var items = ["first", "last"]
items.replaceSubrange(1..<1, with: ["middle"])
print(items) // ["first", "middle", "last"]
Building Arrays with Array Initializers
Sometimes the cleanest approach is creating a new array with the elements you need:
// Repeating an element
let zeros = Array(repeating: 0, count: 5)
print(zeros) // [0, 0, 0, 0, 0]
// From a sequence
let doubled = Array((1...5).map { $0 * 2 })
print(doubled) // [2, 4, 6, 8, 10]
Choosing the Right Method
For most cases, append() and append(contentsOf:) are what you want. They're fast and express intent clearly. Use insert(at:) when position matters, and reach for + when you want a new array without modifying the originals.
If you're adding elements in a loop, prefer building up with append() or consider using reduce(into:) or flatMap() for a more functional approach:
// Instead of this:
var result: [Int] = []
for i in 1...3 {
result.append(contentsOf: [i, i * 10])
}
// Consider this:
let result = (1...3).flatMap { [$0, $0 * 10] }
print(result) // [1, 10, 2, 20, 3, 30]
For more details on array operations, see Apple's Array documentation.
// Continue_Learning
Getting Started with App Intents and Siri Shortcuts
Expose your app's features to Siri, Shortcuts, and Spotlight with App Intents, the Swift-native replacement for SiriKit in iOS 16 and later.
App Tracking Transparency in SwiftUI
A practical guide to App Tracking Transparency in iOS, covering the Info.plist usage description, the ATTrackingManager API, authorization statuses, and when to actually prompt the user from SwiftUI.
withCheckedContinuation vs withUnsafeContinuation in Swift
Continuations bridge completion-handler APIs into async/await. The checked variant catches the two ways you can get it wrong, and the unsafe one trusts you completely.
// Stay Updated
Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.