0
0
Swiftprogramming~5 mins

Set creation and operations in Swift

Choose your learning style9 modes available
Introduction

Sets help you store unique items without order. They make it easy to check if something is there or combine groups without repeats.

You want to keep a list of unique names without duplicates.
You need to find common items between two groups, like friends in both your and your friend's contact list.
You want to add or remove items quickly without caring about order.
You want to find items that are only in one group but not another.
You want to check if an item exists in a collection fast.
Syntax
Swift
var mySet: Set<Type> = [item1, item2, item3]

// Or create an empty set
var emptySet = Set<Type>()

Use Set<Type> to declare a set with a specific type.

Sets automatically remove duplicate items.

Examples
This creates a set of strings with three fruits.
Swift
var fruits: Set<String> = ["apple", "banana", "orange"]
This creates a set of integers. The duplicate 3 is stored only once.
Swift
var numbers = Set([1, 2, 3, 3, 4])
This creates an empty set of integers.
Swift
var emptySet = Set<Int>()
Sample Program

This program creates two sets of numbers and shows how to combine and compare them using set operations. The results are sorted before printing for easier reading.

Swift
import Foundation

var setA: Set<Int> = [1, 2, 3, 4]
var setB: Set<Int> = [3, 4, 5, 6]

// Union: all unique items from both sets
let unionSet = setA.union(setB)

// Intersection: items common to both sets
let intersectionSet = setA.intersection(setB)

// Subtracting: items in setA not in setB
let subtractSet = setA.subtracting(setB)

// Symmetric difference: items in either set but not both
let symDiffSet = setA.symmetricDifference(setB)

print("Union: \(unionSet.sorted())")
print("Intersection: \(intersectionSet.sorted())")
print("Subtracting: \(subtractSet.sorted())")
print("Symmetric Difference: \(symDiffSet.sorted())")
OutputSuccess
Important Notes

Sets do not keep order, so items may appear in any order unless you sort them.

Use sorted() to display sets in order when printing.

Set operations like union, intersection, subtracting, and symmetricDifference help compare groups easily.

Summary

Sets store unique items without order.

You can create sets with Set<Type> and use brackets to list items.

Set operations help combine and compare sets quickly.