Junior
What types of collections exist in Swift?
sobes.tech AI
Answer from AI
There are three main types of collections:
- Arrays: An ordered collection of elements of the same type. Access by index.
- Sets: An unordered collection of unique values of the same type. Efficient element existence check.
- Dictionaries: An unordered collection of key-value pairs. Keys must be unique and of the same type, values of the same type. Access by key.
Examples of creation:
// Array of strings
let fruits: [String] = ["Apple", "Banana", "Cherry"]
// Set of integers
let primeNumbers: Set<Int> = [2, 3, 5, 7, 11]
// Dictionary with String keys and Int values
let ages: [String: Int] = ["Alice": 30, "Bob": 25, "Charlie": 35]
Arrays and dictionaries are ordered in terms of traversal of elements in a loop, although their main characteristic is access by index or key, respectively. Sets do not guarantee traversal order.