Swift Tutorial · Collections and Types · Lesson 12 of 30
Swift Arrays, Dictionaries and Sets
Store values in arrays, dictionaries and sets, and know why Swift collections are value types.
Arrays and sets
Collections declared with let are immutable; with var they can change. They're value types: assigning
an array copies it (cheaply, thanks to copy-on-write), so changing the copy doesn't change the original.
var cart = ["mug"]
cart.append("teapot")
cart.insert("kettle", at: 0)
cart.removeAll { $0 == "mug" }
print(cart, cart.count, cart.first ?? "-")
var copy = cart
copy.append("spoon")
print(cart.count, copy.count) // the original is unchanged
let tags: Set = ["swift", "ios", "swift"]
print(tags.count, tags.contains("ios"))
print(tags.union(["server"]).sorted())
Output
["kettle", "teapot"] 2 kettle 2 3 2 true ["ios", "server", "swift"]
Run this on your computer — see “Get Started” for setup.
Dictionaries
Reading dict[key] returns an optional. dict[key, default: 0] reads with a default and is the idiom for
counting.
let prices = ["mug": 12.0, "teapot": 30.0]
print(prices["mug"] as Any)
print(prices["spoon", default: 0])
var stock: [String: Int] = [:]
for item in ["mug", "mug", "teapot"] {
stock[item, default: 0] += 1
}
for (item, count) in stock.sorted(by: { $0.key < $1.key }) {
print("\(item): \(count)")
}
Output
Optional(12.0) 0.0 mug: 2 teapot: 1
Run this on your computer — see “Get Started” for setup.
Test yourself
What happens to array a after var b = a; b.append(1)?
a also gets the new elementNothing: arrays are value types, so b is a separate copyIt's a compile errora becomes empty
Show answer
Answer: Nothing: arrays are value types, so b is a separate copy