Module 8: Collections in Swift
Collections are used to store multiple values in a single variable. Swift offers three main collection types: Arrays, Sets, and Dictionaries. Understanding how to use these collections effectively is key to managing data in your applications.
Arrays
An Array stores values in an ordered list. You can access elements by their index.
var fruits: [String] = ["Apple", "Banana", "Cherry"]
print(fruits[0]) // Output: Apple
fruits.append("Date")
print(fruits)
Sets
A Set stores unique values without any defined order. Useful when you need to ensure no duplicates.
var colors: Set = ["Red", "Green", "Blue"]
colors.insert("Yellow")
print(colors)
Dictionaries
Dictionaries store key-value pairs. Keys must be unique.
var capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo"]
print(capitals["France"] ?? "Unknown") // Output: Paris
capitals["India"] = "New Delhi"
print(capitals)
Iterating Over Collections
You can loop through collections using for-in
loops.
for fruit in fruits {
print(fruit)
}
for (country, capital) in capitals {
print("\(country): \(capital)")
}
Modifying Collections
Collections are mutable if declared with var
. You can add, remove, or update elements.
fruits.remove(at: 1) // Removes "Banana"
print(fruits)
capitals["France"] = "Lyon" // Updates value
print(capitals)
Summary
- Arrays: ordered collections of values.
- Sets: unordered, unique values.
- Dictionaries: key-value pairs.
- Use loops to iterate over collections.
- Modify collections if mutable.