Sets

A Set in Swift is an unordered collection of unique elements. Unlike an Array, it does not allow duplicate values and does not maintain the order of elements.

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

//Output

["Cherry", "Apple", "Banana"]  // Order may vary

Key Set Operations

//Adding an Element

fruits.insert("Mango")
print(fruits)

//Output
["Cherry", "Apple", "Mango", "Banana"]


//Removing an Element

fruits.remove("Banana")
print(fruits)

//Output
fruits.remove("Banana")
print(fruits)

Set Operations

1. Union

Combines all unique elements from two sets.


let setA: Set = [1, 2, 3]
let setB: Set = [3, 4, 5]
let unionSet = setA.union(setB)
print(unionSet)

//Output
[1, 2, 3, 4, 5]

2.Intersection

Finds common elements between two sets.

let intersectionSet = setA.intersection(setB)
print(intersectionSet)

//Output
[3]

Difference Between Sets and Arrays

FeatureSetArray
OrderUnorderedOrdered
DuplicatesNot allowedAllowed
PerformanceFaster for lookups and operationsSlower for lookups (O(n))
Use CaseEnsuring unique values, mathematical operationsSequential data, maintaining order

Leave a Reply

Your email address will not be published. Required fields are marked *