Swift example

How to concatenate two arrays in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use +: let all = a + b builds a new array and leaves a and b as they were. To add to an existing var in place, write a += b or a.append(contentsOf: b). For one element, call a.append(x), or a.insert(x, at: 0) to put it at the front. An array of arrays flattens with arrays.flatMap { $0 }.

Swift arrays are values, so combining them is simple and safe: + gives you a new array, and the methods that add elements change only the var you call them on. The sections below cover + and +=, adding single elements at the end or at a position, what copying an array really means, the compile error you get when the array is a let, merging without duplicates while keeping the order, and flattening many arrays at once, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1a + b for a new array, += to append in placeRecommended

The + operator joins two arrays of the same element type into a new one. Neither input changes, so both can be let constants. When you want to grow an array you already have, += appends to it in place; it needs a var. The right-hand side doesn't have to be an array: any sequence with the same element type works, such as a slice like numbers[3...] or a range like 6...8. append(contentsOf:) is the method form of += and does the same work.

concat.swift
let fruits = ["apple", "pear"]
let veg = ["kale", "leek"]

// + builds a new array; both inputs stay as they were
let basket = fruits + veg
print(basket)
print(fruits, veg)

// += appends to a var in place
var queue = [1, 2, 3]
queue += [4, 5]
print(queue)

// The right side can be any sequence of the same element type
let numbers = [10, 20, 30, 40, 50]
let picked = [1, 2] + numbers[3...]
print(picked)
queue += 6...8
print(queue)

// append(contentsOf:) is the method form of +=
var letters: [Character] = ["a", "b"]
letters.append(contentsOf: "cd")
print(letters)

Output

basket holds all four items, and printing fruits and veg afterwards shows them unchanged. queue += [4, 5] grows the array to [1, 2, 3, 4, 5], the slice adds 40, 50, and the range adds 6, 7, 8. A String is a sequence of Character, so append(contentsOf: "cd") adds two letters. The order of the operands matters: an array on the left gives an Array, while numbers[3...] + [1] gives an ArraySlice<Int>, the type of the left side.

2Add one element: append and insert(_:at:)

append(_:) adds a single element at the end, which is the cheap end of an array. insert(_:at:) puts an element at an index and shifts everything after it one place to the right, so inserting near the front of a long array costs time proportional to its length. insert(contentsOf:at:) does the same for several elements. The valid positions run from 0 to count; at: count means the end. To prepend a whole array, put it first in a +.

add_one.swift
var tasks = ["write", "test"]

// One element at the end
tasks.append("ship")
print(tasks)

// One element at a position: the rest shift right
tasks.insert("plan", at: 0)
print(tasks)

// Several elements at a position
tasks.insert(contentsOf: ["review", "fix"], at: 3)
print(tasks)

// at: tasks.count is the end, the same as append
tasks.insert("celebrate", at: tasks.count)
print(tasks)

// += needs an array (or other sequence) on the right
tasks += ["rest"]
print(tasks.count, tasks.last ?? "none")

// Prepend a whole array
let urgent = ["hotfix"]
tasks = urgent + tasks
print(tasks.first ?? "none")

Output

Each line shows the array after one call: plan lands at index 0, review and fix go in before ship at index 3, and at: tasks.count adds celebrate at the end. A single value needs brackets with +=: tasks += ["rest"] works, while xs += 3 fails with cannot convert value of type 'Int' to expected argument type 'Array<Int>'. The compiler can't catch an index past count; it crashes at run time: xs.insert(9, at: 5) on a three-element array stops with Fatal error: Array index is out of range.

3Arrays are values: appending to a copy

Assigning an array to another variable, or passing it to a function, gives the new name its own copy. Appending to that copy never changes the original. Swift makes this cheap with copy-on-write: the two arrays share one buffer until one of them is changed, and only then is the storage copied. When a function really should change the caller's array, mark the parameter inout and pass it with &. One thing is not copied: if the elements are class instances, both arrays hold references to the same objects.

values.swift
let original = [1, 2, 3]

// Assigning an array copies it (cheaply: storage is shared until a write)
var copy = original
copy.append(4)
print("original:", original)
print("copy:    ", copy)

// The same holds for function arguments: the caller's array is safe
func appended(_ xs: [Int], _ x: Int) -> [Int] {
    var result = xs
    result.append(x)
    return result
}
let longer = appended(original, 99)
print(original, longer)

// inout lets a function change the caller's array
func addZero(to xs: inout [Int]) {
    xs.append(0)
}
var counts = [5, 6]
addZero(to: &counts)
print(counts)

// Class elements are references: both arrays point at the same objects
final class Box {
    var value: Int
    init(_ value: Int) { self.value = value }
}
let boxes = [Box(1), Box(2)]
let more = boxes + [Box(3)]
more[0].value = 100
print(boxes.map(\.value), more.map(\.value))

Output

After copy.append(4), original is still [1, 2, 3]. The function works on its own copy too, so the caller sees [1, 2, 3] [1, 2, 3, 99], and only the inout version changes counts to [5, 6, 0]. The last line is the exception: more is a separate array, but its first two elements are the same Box objects as in boxes, so setting more[0].value shows up as [100, 2] in both. With structs as elements, the arrays would be fully independent.

4The compile error: appending to a let array

append, insert and += change the array, so they only work on a var. Call one on a let constant and the program doesn't compile. The program below never runs.

let_append.swift
let primes = [2, 3, 5]
primes.append(7)
print(primes)

Output

The compiler stops with error: cannot use mutating member on immutable value: 'primes' is a 'let' constant and a note on line 1: change 'let' to 'var' to make it mutable. Do that, or keep the let and build a new constant with let more = primes + [7]. Function parameters are constants too: xs.append(10) inside func addTen(_ xs: [Int]) gives the same error for 'xs'. Copy it into a local var first, as appended does in section 3, or use inout.

5Merge without duplicates, keeping the order

a + b keeps every element, duplicates included. To merge and drop repeats, filter the combined array through a Set of the values seen so far: seen.insert(x).inserted is true only the first time a value turns up, so the first occurrence wins and the order is kept. The elements must be Hashable. Set(a).union(b) also removes duplicates, but a set has no order: it iterates in a different order from run to run, so sort it if you need a stable result. Checking with array.contains instead of a set gives the same answer but scans the whole array for every element (more in check if an array contains a value).

merge_unique.swift
let morning = ["ben", "ana", "cy", "ben"]
let evening = ["dee", "cy", "ana", "eve"]

// Keep the first occurrence of each value, in order
func uniqued<T: Hashable>(_ items: [T]) -> [T] {
    var seen = Set<T>()
    return items.filter { seen.insert($0).inserted }
}
print(uniqued(morning + evening))

// Only add the items of evening that roster doesn't already have
var roster = ["zoe", "ana"]
let present = Set(roster)
roster += evening.filter { !present.contains($0) }
print(roster)

// A Set union removes duplicates but has no order: sort it to print
let union = Set(morning).union(evening)
print(union.count, union.sorted())

// Two sorted arrays into one sorted array
let a = [1, 4, 9]
let b = [2, 3, 10]
print((a + b).sorted())

Output

uniqued keeps ben first because it appeared first, and drops the second ben and the evening repeats of cy and ana. The roster version adds only dee, cy and eve, leaving the existing items where they were; it does not remove duplicates that are already inside evening, so run it through uniqued too if that can happen. The set has the same 5 names, but union.sorted() lists them alphabetically, so ben is no longer first. For sorted inputs, (a + b).sorted() is the short way to a sorted result.

6Many arrays at once: joined() and flatMap

When you have an array of arrays, joined() concatenates all of them. It returns a lazy view rather than an array, so wrap it in Array(…) when you need one. flatMap { $0 } does the same and returns an Array directly. Both flatten one level only. joined(separator:) puts a separator array between the groups. When you append many arrays in a loop and know the final size, reserveCapacity(_:) allocates the space once instead of growing the buffer several times along the way.

flatten.swift
let weeks = [[3, 1], [4, 1, 5], [], [9, 2]]

// joined() flattens one level and returns a lazy view; wrap it in Array
let flat = Array(weeks.joined())
print(flat)

// flatMap { $0 } does the same and gives an Array directly
print(weeks.flatMap { $0 })

// A separator between the groups
print(Array(weeks.joined(separator: [0])))

// Only one level: deeper nesting stays nested
let nested = [[[1, 2], [3]], [[4]]]
print(nested.flatMap { $0 })

// Building a big array: reserve the space first
let parts = [Array(1...3), Array(4...6), Array(7...9)]
var all: [Int] = []
all.reserveCapacity(parts.reduce(0) { $0 + $1.count })
for part in parts {
    all += part
}
print(all, all.count, all.capacity >= 9)

Output

Both forms give [3, 1, 4, 1, 5, 9, 2], and the empty group simply contributes nothing. With a separator, the empty group still gets one on each side, which is why two zeros appear in a row. The three-level array comes out as [[1, 2], [3], [4]]: call flatMap { $0 } again to go one level further. Without Array(…), weeks.joined() has the type FlattenSequence<Array<Array<Int>>>. You may see parts.reduce([], +) in older answers; it gives the same array but builds a new array at every step, so prefer joined() or flatMap.

7Which should you use?

MethodChanges the arrayResultBest for
a + bNoNew arrayJoining two arrays into a new one
a += b / a.append(contentsOf: b)Yes, needs vara growsAdding a whole array or sequence to the end
a.append(x)Yes, needs vara growsAdding one element
a.insert(x, at: i)Yes, shifts the resta growsAdding at the front or in the middle
uniqued(a + b)NoNew array, order keptMerging without duplicates
Set(a).union(b)NoSet, no orderMembership tests, when order does not matter
arrays.flatMap { $0 }NoNew arrayMany arrays or one level of nesting
arrays.reduce([], +)NoNew array at every stepNothing: use flatMap or joined()

Frequently asked questions

How do I add an element to the beginning of an array in Swift?

Call array.insert(x, at: 0), or array = [x] + array. Both move every existing element one place, so the cost grows with the array. If you add many elements to the front, append them instead and call reverse() once at the end.

Why does xs += 3 not compile?

+= on an array expects another array or sequence on the right, so a single value fails with "cannot convert value of type 'Int' to expected argument type 'Array<Int>'". Wrap it in brackets, xs += [3], or call xs.append(3).

Is append(contentsOf:) faster than +=?

No, they do the same work: += with a sequence on the right appends its elements to the array on the left, just like append(contentsOf:). Pick whichever reads better. a = a + b is different: it builds a new array and then assigns it back.

Can I concatenate arrays of different types?

Not directly: ids + names with an [Int] and a [String] fails with "binary operator '+' cannot be applied to operands of type '[Int]' and '[String]'". Convert one side first, as in ids.map(String.init) + names, or wrap both in an enum with a case for each type. Declaring the result as [Any] compiles, but every element then has to be cast back before you can use it, so avoid it.

What happens if I insert at an index past the end?

The program crashes with Fatal error: Array index is out of range. The valid positions for insert(_:at:) are 0 through count, where count means the end. Check the index first, or use append when you mean the end.

Does a + b copy the elements?

It creates a new array and leaves both inputs unchanged. Value elements such as Int, String or a struct are copied. Class instances are references, so the new array points at the same objects: changing a property through one array shows up in the other.

How do I flatten an array of arrays in Swift?

Use arrays.flatMap { $0 } for an Array, or Array(arrays.joined()). Both remove one level of nesting; repeat for deeper arrays. flatMap that drops nil values was renamed compactMap in Swift 4.1, which is why older answers use flatMap for both jobs.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground