We can create sets in Swift. It can be either empty or filled with values. The term “empty set” refers to a set that has been created without any values. We can use empty sets when we aren’t sure what specific data we will store in our set.
The syntax for creating an empty set is as follows:
var setName = Set<Type>();
Setkeyword followed by the data type of the elements in the set to create it.
()to the end of the statement to indicate that we are creating an empty set.
For example, we can make an empty set to store the names of the various instruments we play:
var music = Set<String>();
It’s worth noting how we specify that the values of this set will be of the type
String. We’ll get the following output if we print this empty set:
We have the option of creating a populated set as well. When we already know what data we want to store, we can start a set with values. We can use the following syntax to create a populated set:
var setName: Set = [Value1, Value2, Value3];
Setkeyword must be used.
,and must be contained within brackets
If we wanted to make a set that contain members names of the codeofcode team, we would write the following code:
var cocTeam: Set = ["Alina", "Lara", "Merri", "Kevin"]; print(cocTeam); //["Lara", "Merri", "Alina", "Kevin"]
It’s worth noting how the elements were printed in a different order than they were initialized.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.