Properties2
TypeConcept
Note createdFeb 17, 2025

In Swift, there are several ways to store different collections of data. Most of them are similar to other modern languages.

Arrays

Arrays in Swift are defined using squared brackets and its length can be modified at runtime. Some relevant functions for arrays are:

  • Declaring them using let numbers = Array<Int>() or let numbers = [Int].
  • Accessing arrays using numbers[0].
  • Checking its length using numbers.count.
  • Adding elements using beatles.append("Ringo").
  • Removing elements using numbers.remove(at: 2).
  • Checking if an element is present using numbers.contains(3).
  • Sorting the array using numbers.sorted() (returns a value, it is not in-place).
  • Reversing an array using numbers.reversed() (again, not in-place).

Dictionaries

In Swift, dictionaries are defined using a very similar syntax to arrays, but adding key-value pairs.

let example = [
	"name": "Taylor Swift",
	"job": "Singer",
	"location": "Nashville"
]

Accessing an element will return an Optional value, to allow for error handling when accessing the dictionary. An easy way to unpack the value is to provide a default value for it:

let job = example["job", default: "unknown"]

Sets

Swift provides sets for faster data lookup, which can be created using an array literal:

let people = Set(["Denzel Washington", "Tom Cruise", "Nicolas Cage", "Samuel L Jackson"])

As expected, sets contain non-duplicated elements and are useful for faster .contains operations.