Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Sets in Swift

Understanding Sets in Swift

What is a Set?

A set is a collection type in Swift that stores unique values of the same type in a collection. Sets are unordered, meaning the elements do not have a specific order and are not indexed. This makes sets ideal for use cases where uniqueness is a requirement.

Creating a Set

To create a set in Swift, you can use the Set initializer. Here's how you can declare a set:

var fruits: Set<String> = ["Apple", "Banana", "Cherry"]

This creates a set of strings containing three unique fruits.

Adding and Removing Elements

You can add elements to a set using the insert() method and remove elements using the remove() method:

fruits.insert("Orange")
fruits.remove("Banana")

After executing these commands, "Orange" will be added to the set, and "Banana" will be removed.

Accessing Sets

Since sets are unordered, you cannot access elements by index. However, you can loop through a set or check if it contains a specific value using the contains() method:

if fruits.contains("Apple") {
print("Apple is in the set")
}

Set Operations

Swift sets provide various operations such as union, intersection, and subtraction:

let tropicalFruits: Set<String> = ["Mango", "Pineapple", "Banana"]
let allFruits = fruits.union(tropicalFruits)

This example combines two sets into a new set called allFruits that contains all unique fruits from both sets.

Example: Using Sets

Let's look at a complete example that demonstrates the use of sets:

var colors: Set<String> = ["Red", "Green", "Blue"]
colors.insert("Yellow")
colors.remove("Green")
for color in colors {
print(color)
}

This code initializes a set of colors, adds "Yellow", removes "Green", and prints all remaining colors.

Conclusion

Sets are a powerful collection type in Swift that help manage unique values efficiently. Understanding how to create, modify, and access sets will enhance your ability to handle collections effectively in your Swift applications.