Learn
Sets
Creating a Set

In Swift, we can initialize sets that are either empty or populated with values.

A set that has been initialized without any values inside of it is known as an empty set. Empty sets are useful when we aren’t sure what specific data we are going store within our set yet.

The syntax for creating an empty set looks like this:

var setName = Set<Type>()
  • To initialize a set, use the Set keyword followed by the data type of the elements it will contain.
  • To signify we are creating an empty set, add parentheses () at the end of the statement.

For example, we can create an empty set that will store the names of the types of instruments we play:

var instruments = Set<String>()

Note how we state that the values of this set will be type String. When we print this empty set, we will get the following output:

[]

We also have the option to create a populated set. Initializing a set with values is useful when we already know what data we want to store.

To create a populated set, we can use the following syntax:

var setName: Set = [Value1, Value2, Value3]
  • We must use the Set keyword.
  • All values must be contained within brackets [] and each value is separated by a comma ,.
  • There are no repeated values.
  • The elements of the set must all be the same type.

If we wanted to create a set that stores members of the Swift team, our code would look like this:

var swiftTeam: Set = ["Galina", "Kenny", "Sonny", "Alex"]

Sets are unordered, meaning that the placement of an element in a set will not dictate how it is interpreted by the compiler. For example, if we tried to print the value of swiftTeam:

print(swiftTeam)

We could get the following output:

["Alex", "Galina", "Sonny", "Kenny"]

Notice how the order that the elements were printed is different than the order in which they were initialized. The order of execution in a set could look different every time a program is run.

Instructions

1.

Create an empty set called consonants with Character type values.

2.

Create a second set called vowels that contains the following values: "A", "E", "I", "O", "U".

Output vowels to the terminal.

Folder Icon

Take this course for free

Already have an account?