Swift Collections

Swift Collections (Sets and Dictionaries)

In addition to Arrays, Swift provides two other primary collection types for storing data: Sets and Dictionaries.

Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

Understanding when to use which collection type is critical for writing efficient Swift code.


Sets

A Set stores distinct values of the same type in a collection with no defined ordering.

You use a Set instead of an Array when the order of items is not important, or when you need to ensure that an item only appears once.

Creating a Set:

// Explicitly defining a Set
var genres: Set<String> = ["Rock", "Classical", "Hip hop"]

// Adding an element genres.insert("Jazz")

print(genres)

Because Sets are unordered, the printed output may display the items in a different order each time you run the code.


Dictionaries

A Dictionary stores associations between keys of the same type and values of the same type.

Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Think of it like a real-world dictionary looking up a definition.

Creating a Dictionary:

// Key is String, Value is Int
var playerScores: [String: Int] = ["Alice": 100, "Bob": 85]

// Accessing a value by key print(playerScores["Alice"]!) // Outputs 100

// Adding or updating a value playerScores["Charlie"] = 120


Choosing the Right Collection


Exercise

Which Swift collection type should you use to store items if you want to ensure there are no duplicate values?