SWIFT / CHAPTER 06

Arrays, dictionaries, and value copies

Intermediate

Update collections while preserving intended independence.

By the end of this chapter

  • Trace array value semantics
  • Use dictionary defaults
  • Handle empty collections before removal

The idea

Swift arrays and dictionaries are value types. Assigning an array to a new variable gives it independent value semantics: changing the new array’s elements does not change the original array value. Implementations may share storage internally until mutation, but that optimization does not change the observable value model. Arrays hold ordered elements; dictionaries associate unique keys with values.

A dictionary lookup normally returns an optional because a key might be absent. The default subscript can supply a starting value for a counting operation. Collection mutating operations still have preconditions: removeFirst requires a nonempty array. Check emptiness or use an operation whose result explicitly represents absence before removing an item from a possibly empty queue.

Swift example
var first = [2, 4]
var second = first
second.append(6)
var counts: [String: Int] = [:]
for tag in ["bug", "docs", "bug"] { counts[tag, default: 0] += 1 }
print(first.count)
print(second.count)
print(counts["bug", default: 0])
Result
2
3
2

The appended element belongs to second’s array value. Dictionary updates begin missing counts at zero, then increment the selected key.

Try it yourself

Count repeated labels in a dictionary, then read a missing label with a zero default.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
var a = [1, 2]
var b = a
b[0] = 9
print(a[0])