4.3 Sets
A set stores distonct values of the same type in a collection with no distinct ordering. Sets can be used in place of arrays when:
- The order of items is not important
- When you need to ensure an item appears only once.
A type must be hashable in order to be stored in a set. This means that it must provide a way to compute a hash value for itself. A hash value is an Int
value that's the same for all values that compare equality, such that, if a == b
, it must follow that a.hashvalue == b.hashvalue
All of Swift's basic types (Int
, String
, Double
, Bool
etc.) are hashable by default, and can be used as set value types. This is also true for Enumeration case values without associated data.
You can make your own custom types Hashable
by making them conform to the Hashable
protocol. As the Hashable protocal inherits from Equatable
, it must also conform to this. Details of how to do this are provided in the Swift Documentation for Hashable and Equatable.
You can create an empty set using the initializer syntax:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."
Note that, unlike arrays and dictionaries, sets do not have an equivalent shorthand syntax. However, the array syntax can be substituted in various ways. For instance, if you have already provided the set with type information, you can create an empty set using an empty array literal, []
:
letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>
You can also initialize a set with an array literal, as in:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
Note that we needed the :Set
type declaration to be made explicitly because without it, type inference would assume an array. However, we could have omitted the <String>
portion, as Swift can recognise that it will be a set of strings. In other words, the following is valid:
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
Sets provide a standard set of methods and properties allowing the user to access and modify them. These include:
count
- an integer property to find the number of items in a setisEmpty
- a boolean property which tells you if a set contains 0 elementsinsert(_:)
- a method to add an item to a setremove(_:)
- This removes an item from the set and returns it if it's a member of the set, and returnsnil
if it is not.removeAll()
- This removes all the members of a set.
You can iterate over a set using a standard for-in
loop. Note however that sets do not have a defined ordering. If you want the values in a specific order, you can use the sorted()
method, which returns the sets elements as an array sorted using the <
operator:
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
// Classical
// Hip hop
// Jazz