Arrays and dictionaries in Swift
Value-type collections with literal syntax.
// Arrays and dictionaries are value types with literal syntax.
var fleet = ["Kestrel", "Sable"]
fleet.append("Petrel")
fleet.insert("Brant", at: 0)
print("\(fleet.count) boats, first away: \(fleet[0])")
var sailNumbers: [String: Int] = ["Kestrel": 207]
sailNumbers["Petrel"] = 415
sailNumbers["Sable"] = 88
// Updating returns the old value, Optional of course.
let old = sailNumbers.updateValue(89, forKey: "Sable")
print("Sable was #\(old ?? 0), now #\(sailNumbers["Sable"] ?? 0)")
print(fleet.contains("Osprey"))
How it works
appendandinsert(_:at:)grow an array.- Subscript assignment writes a dictionary key.
updateValuereturns the old value — Optional, naturally.
Keywords and builtins used here
IntStringcontainscountinsertletprintvar
The run, in numbers
- Lines
- 14
- Characters to type
- 518
- Tokens
- 135
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 116 seconds.
Step 1 of 3 in Collections, step 13 of 27 in Language basics.