Collections and data structures

Section 1.6: Collections and Data Structures


In this section, we'll explore Swift's powerful tools for organizing and managing collections of data: arrays, sets, and dictionaries. These data structures are essential for storing and manipulating multiple values efficiently in your applications.


Arrays: Ordered Collections of Values


An array is a fundamental data structure that stores an ordered list of values of the same type. You can think of it as a row of boxes, each containing a specific item.


Declaration:

Swift

var numbers: [Int] = [1, 2, 3, 4, 5]  // An array of integers

var names: [String] = ["Alice", "Bob", "Charlie"] // An array of strings


Accessing Elements: You can access elements in an array using their index (starting from 0).

Swift

print(numbers[0]) // Output: 1


Common Operations: Adding/removing elements, inserting at a specific index, counting elements, finding elements, sorting.

Sets: Unordered Collections of Unique Values


A set is a collection of unique values of the same type, where the order of elements is not important. Sets are ideal for checking membership and eliminating duplicates.


Declaration:

Swift

var uniqueNumbers: Set<Int> = [1, 2, 3, 4, 5]

var uniqueNames: Set<String> = ["Alice", "Bob", "Charlie"]


Common Operations: Adding/removing elements, checking for membership (contains), set operations (union, intersection, difference).

Dictionaries: Key-Value Pairs


A dictionary is a collection of key-value pairs, where each key is associated with a corresponding value. Keys are unique, and values can be of any type.


Declaration:

Swift

var ages: [String: Int] = ["Alice": 25, "Bob": 30, "Charlie": 35]


Accessing Values: You can access values in a dictionary using their keys.

Swift

print(ages["Alice"]) // Output: Optional(25)


Common Operations: Adding/removing key-value pairs, updating values, iterating over keys and values.

Choosing the Right Collection:


Array: Use when you need to maintain the order of elements and access them by index.

Set: Use when you need to store unique values and don't care about their order.

Dictionary: Use when you need to associate values with unique keys.

Key Takeaways:


Collections are fundamental data structures for storing and managing multiple values.

Arrays store ordered lists of values of the same type.

Sets store unordered collections of unique values of the same type.

Dictionaries store unordered collections of key-value pairs.

By understanding the different types of collections and their operations, you can choose the right data structure for your specific needs and write more efficient and organized Swift code.

Course Syllabus