Junior
Tell me about collections in Swift and their features.
sobes.tech AI
Answer from AI
Swift provides three main built-in collections: Arrays, Sets, and Dictionaries. All of them are mutable or immutable depending on whether they are declared with var or let, and they are generic types, allowing storage of elements of any type, provided all elements in the collection are of the same type.
Arrays
- Ordered collection of elements of the same type.
- Access to elements is by index.
- Can contain duplicate elements.
// Empty array of strings
var strings: [String] = []
// Array of integers
let numbers = [1, 2, 3, 4, 5]
// Adding an element
strings.append("Hello")
// Access by index
let firstElement = numbers[0] // 1
Sets
- Unordered collection of unique elements of the same type.
- Elements must be hashable (conform to the
Hashableprotocol). - Used for checking uniqueness and fast searches.
// Empty set of integers
var uniqueNumbers: Set<Int> = []
// Set of strings
let colors: Set = ["red", "green", "blue"]
// Insert an element
uniqueNumbers.insert(10) // Adds only if 10 is not already in the set
// Check for presence
let hasRed = colors.contains("red") // true
Dictionaries
- Unordered collection of key-value pairs, where keys are unique.
- Keys must be hashable.
- Used for fast lookup of values by key.
// Empty dictionary with string keys and integer values
var ages: [String: Int] = [:]
// Dictionary of cities and their populations
let population = ["Moscow": 12_600_000, "Saint Petersburg": 5_400_000]
// Add or update value by key
ages["Alice"] = 30
// Access value by key (returns Optional)
let moscowPopulation = population["Moscow"] // Optional(12600000)
// Remove an element
ages["Alice"] = nil
Features:
- Type safety: Swift requires all elements in a collection to be of the same type.
- Type inference: In many cases, the compiler can automatically determine the element type.
- Iteration: All collections support iteration using
for-inloops. - Protocols: Collections conform to various protocols such as
Collection,Sequence,MutableCollection. Sets and dictionary keys require conformance toHashable. - Efficiency: Swift optimizes various collection operations for performance.