Set
The set type is a generic collection that is similar to the array type. While the array type is an ordered collection that may contain duplicate items, the set type is an unordered collection where each item must be unique.
Like the key in a dictionary, the type stored in an array must conform to the Hashable protocol. This means that the type must provide a way to compute a hash value for itself. All of Swift's basic types, such as String
, Double
, Int
, and Bool
, conform to this protocol and can be used in a set by default.
Let's look at how we would use the set type.
Initializing a set
There are a couple of ways to initialize a set. Just like the array and dictionary types, Swift needs to know what type of data is going to be stored in it. This means that we must either tell Swift the type of data to store in the set or initialize it with some data so that it can infer the data type.
Just like the array and dictionary types, we use the var
and let...