typestar

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

  1. append and insert(_:at:) grow an array.
  2. Subscript assignment writes a dictionary key.
  3. updateValue returns the old value — Optional, naturally.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Collections, step 13 of 27 in Language basics.

← Previous Next →