Part of Swift with Copilot

Swift: Merge 2 integer arrays

Sandy LaneSandy Lane

Video: Swift: Merge 2 integer arrays by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Swift with Copilot: Merge 2 Integer Arrays

a + b concatenates two arrays. a.append(contentsOf: b) extends in place. For sorted-merge: (a + b).sorted() or zip-walk. For unique union: Array(Set(a + b)).

Combining two arrays — three common interpretations: concat, sort-merge, deduplicated union.

The Copilot prompt

// Merge two arrays of integers
let a = [1, 2, 3]
let b = [4, 5, 6]

Copilot completes:

let a = [1, 2, 3]
let b = [4, 5, 6]
let merged = a + b
print(merged)
// [1, 2, 3, 4, 5, 6]

+ operator

[1, 2, 3] + [4, 5, 6]
// [1, 2, 3, 4, 5, 6]

Array's + returns a new array — operands unchanged. Allocates a fresh buffer; copies both.

For multiple arrays:

let a = [1, 2]
let b = [3, 4]
let c = [5, 6]
let merged = a + b + c    // [1, 2, 3, 4, 5, 6]

In-place: append(contentsOf:)

var a = [1, 2, 3]
let b = [4, 5, 6]
a.append(contentsOf: b)
print(a)
// [1, 2, 3, 4, 5, 6]

append(contentsOf:) extends a with b's elements. a is modified in place — needs var.

Faster for repeated extensions because Array can grow its existing buffer instead of allocating a new one each time.

There's also +=:

a += b    // same as a.append(contentsOf: b)

Sorted merge

let a = [1, 3, 5]
let b = [2, 4, 6]
let merged = (a + b).sorted()
// [1, 2, 3, 4, 5, 6]

Concatenate then sort. O((n+m) log (n+m)).

If both inputs are already sorted and you want O(n+m), zip-walk:

func merge<T: Comparable>(_ a: [T], _ b: [T]) -> [T] {
  var result = [T]()
  result.reserveCapacity(a.count + b.count)
  var i = 0, j = 0
  while i < a.count && j < b.count {
    if a[i] <= b[j] {
      result.append(a[i])
      i += 1
    } else {
      result.append(b[j])
      j += 1
    }
  }
  result.append(contentsOf: a[i...])
  result.append(contentsOf: b[j...])
  return result
}

Classic merge step from mergesort. For most apps, (a + b).sorted() is fine — only optimize when n is huge and a/b are pre-sorted.

Unique union (deduped)

let a = [1, 2, 3, 4]
let b = [3, 4, 5, 6]
let union = Array(Set(a + b))
// [1, 2, 3, 4, 5, 6] — order not guaranteed

Set(...) deduplicates; Array(...) materializes. Order is not preserved — Set is hash-based.

To preserve original order:

var seen = Set<Int>()
let unique = (a + b).filter { seen.insert($0).inserted }
// [1, 2, 3, 4, 5, 6] — first-occurrence order

Set.insert(_:) returns a tuple (inserted: Bool, memberAfterInsert: Element). Filter keeps elements that weren't already in the set.

Intersection

let a = [1, 2, 3, 4]
let b = [3, 4, 5, 6]
let common = Set(a).intersection(b)
// [3, 4] — Set, not Array

let array = Array(common)

Set has built-in set operations: union, intersection, subtracting, symmetricDifference.

let s1: Set = [1, 2, 3, 4]
let s2: Set = [3, 4, 5, 6]

s1.union(s2)               // [1, 2, 3, 4, 5, 6]
s1.intersection(s2)        // [3, 4]
s1.subtracting(s2)         // [1, 2]
s1.symmetricDifference(s2) // [1, 2, 5, 6]

For Array<Int>, wrap with Set(...).

Difference

let a = [1, 2, 3, 4]
let b = [2, 4]
let diff = a.filter { !b.contains($0) }
// [1, 3]

For large arrays, prefer Set:

let setB = Set(b)
let diff = a.filter { !setB.contains($0) }

Set.contains is O(1); Array.contains is O(n). For repeated lookups, hash once.

Performance

Operation Time
a + b O(n + m)
a.append(contentsOf: b) amortized O(m)
(a + b).sorted() O((n+m) log(n+m))
Sorted merge (zip-walk) O(n + m)
Set(a + b) (dedup) O(n + m)
a.contains(x) O(n) per lookup
Set(a).contains(x) O(1) per lookup, O(n) build

For most realistic sizes, all are fast. For repeated set operations, build the Set once.

Multiple arrays at once

let arrays = [[1, 2], [3, 4], [5, 6]]
let flat = arrays.flatMap { $0 }
// [1, 2, 3, 4, 5, 6]

flatMap { $0 } is the idiom for "flatten one level." Works for any nested-array depth-1.

Common stumbles

Trying to mutate let. let a = [1, 2]; a += b errors. Use var.

+ is allocating. For loops that build incrementally, prefer append(contentsOf:) or +=.

Array(Set(...)) loses order. Set is unordered. Use the seen.insert($0).inserted pattern for order-preserving dedup.

a.contains(x) in a loop. O(n) per call → O(n²) total. Hash to a Set first.

Type mismatch. [1, 2] + ["a"] errors — different element types. Both arrays must have the same Element.

+ with nil. Arrays aren't optional by default. If one might be nil: (a ?? []) + b.

What's next

Episode 17: Remove duplicates from array. The dedup pattern in detail.

Recap

a + b concatenates (immutable). a.append(contentsOf: b) or a += b for in-place. For sorted output: (a + b).sorted(). For dedup: Array(Set(a + b)) (unordered) or filter with Set.insert.inserted (ordered). For set ops, convert to Set and use union/intersection/subtracting. flatMap { $0 } to merge nested arrays.

Next episode: remove duplicates.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.