Array Methods in Swift

Level 2110 keystrokes

Adds elements with append and insert(_:at:), prints the array ["x", "a", "b", "c"] and reads the first element with first.

Swift code

// Declared with var so the array can be modified
1var items = ["a", "b"]
// append adds to the end: ["a", "b", "c"]
2items.append("c")
// insert(_:at:) puts "x" at index 0 and shifts the rest right
3items.insert("x", at: 0)
// Prints the whole array: ["x", "a", "b", "c"]
4print(items)
// first is optional (nil for an empty array); ! force-unwraps it: First: x
5print("First: \(items.first!)")

Output

["x", "a", "b", "c"]
First: x
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 10
  • (× 5
  • )× 5
  • .× 3
  • ,× 2
  • :× 2
  • !× 1
  • [× 1
  • ]× 1
  • \× 1

More Swift examples at level 2

← Swift typing practice