Swift collection types
A collection groups multiple items into a single unit. Swift provides three native collection types. These collection types are arrays, sets, and dictionaries. Arrays store data in an ordered collection, sets are unordered collections of unique data, and dictionaries are unordered collections of key/value pairs. In an array, we access the data by the location (index) in the array; in a set, we tend to iterate over the set; and dictionaries are usually accessed using a unique key.
The data stored in a Swift collection is required to be of the same type. This means, as an example, that we are unable to store a string value in an array of integers. Since Swift does not allow us to mismatch data types in a collection, we can be certain of the data type when we retrieve an element from a collection. This is another feature that, on the surface, might seem like a shortcoming but actually helps eliminate common programming mistakes.
Note
Having a collection that contains arbitrary data types usually leads to problems and should be considered a design problem. Later in this chapter, we will see how to use the Any
and AnyObject
aliases, but we should avoid this wherever possible.