Swift Sets

A set in Swift is similar to an array, with their ability to store multiple values of the same type, however, the elements within are unique and in no particular order. A set can be defined as follows.

var fnames:Set = [ "Bob", "George", "Fred", "Alan" ]

As with ordinary variables and arrays, an empty set can be defined if the type is specified.

var fnames:Set<String> = []

Values can then be added to the set using the 'insert' method. If an attempt is made to add an element that is already present, no error is produced and the value isn't added.

fnames.insert("Bob")
fnames.insert("George")
fnames.insert("Fred")
fnames.insert("Alan")

In order to display all of the elements in a set, a ‘for’ loop can be used.

for name in fnames
{
    print(name)
}

The resulting output will list all the elements of the set on a separate line. Note that the order of the elements may not be the same as that shown each time the above code is run.

Bob
George
Fred
Alan

If it is necessary to have the elements in order, then the 'sorted' method can be used to achieve this.

for name in fnames.sorted()
{
    print(name)
}

In terms of inspecting a set, it is possible to check if a set is empty by using the 'isEmpty' property. Here, an 'if' statement is used to check if the set is empty. If it isn't the names are displayed, otherwise a message is displayed.

var fnames:Set<String> = []

if !fnames.isEmpty
{
    for name in fnames.sorted()
    {
        print(name)
    }
}
else
{
    print("There are no names in the set.")
}

An alternative way to achieve the same result, would be to use the 'count' property, which holds the number of elements in the set.

var fnames:Set<String> = []

if fnames.count != 0
{
    for name in fnames.sorted()
    {
        print(name)
    }
}
else
{
    print("There are no names in the set.")
}

The above displays the names only if the count of the number of elements in the set is not equal to zero.

There is also a 'contains' method, that can be used to check if a value exists within a set. The example below checks whether the name, 'George', exists within the set and displays a message accordingly.

var fnames:Set = [ "Bob", "George", "Fred", "Alan" ]

if fnames.contains("George")
{
    print("The name George is in the set.")
}
else
{
    print("The name George is not in the set.")
}

If it is a requirement to remove a single element, this can be done by using the 'remove' method and specifying the value.

fnames.remove("George")

In order to empty a set completely, the 'removeAll' method can be used.

fnames.removeAll()

Further Reading