Module 8: Collections in Swift – Arrays, Sets & Dictionaries Explained

Module 8: Collections in Swift – Arrays, Sets & Dictionaries Explained

AI Reading

Quick summary of this article

Swift provides three main collection types—Arrays, Sets, and Dictionaries—to store multiple values in a single variable. Arrays keep values in an ordered list, Sets store unique values without order, and Dictionaries hold key-value pairs with unique keys. These collections can be modified if declared with var, and you can loop through them using for-in loops.

  • Arrays store values in a specific order, accessed by index (e.g., fruits[0]).
  • Sets contain only unique values and have no defined order, useful for avoiding duplicates.
  • Dictionaries store data as key-value pairs, with each key being unique.
  • Use for-in loops to iterate over any collection, including key-value pairs in dictionaries.
  • Collections declared with var are mutable, allowing you to add, remove, or update elements.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *