> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Set

A `Set` in Swift is a generic, unordered collection that stores distinct values of the same type. To be stored in a set, a type must conform to the `Hashable` protocol, which allows the collection to compute a hash value for each element. This hash value guarantees uniqueness and enables $O(1)$ constant-time complexity for lookups, insertions, and deletions.

## Initialization

Because Swift's array literals are used to initialize both arrays and sets, you must explicitly declare the `Set` type to prevent the compiler from inferring an `Array`.

```swift theme={"dark"}
// Initializing an empty set
var emptyIntSet = Set<Int>()

// Initializing with an array literal using explicit type annotation
var stringSet: Set<String> = ["Apple", "Banana", "Cherry"]

// Initializing with type inference (type is inferred as Set<Double>)
var doubleSet: Set = [1.5, 2.0, 3.14]
```

## Core Properties and Inspection

Sets provide standard collection properties to inspect their state and contents.

```swift theme={"dark"}
let count = stringSet.count          // Returns the number of elements
let isEmpty = stringSet.isEmpty      // Returns a Boolean indicating if count == 0

// Constant-time O(1) membership check
let containsApple = stringSet.contains("Apple") 
```

## Mutating Operations

When modifying a set, operations often return tuples or optionals to indicate the success of the mutation or the previous state of the collection.

```swift theme={"dark"}
// Insertion returns a tuple: (inserted: Bool, memberAfterInsert: Element)
let insertResult = stringSet.insert("Date")
// insertResult.inserted is true if "Date" was not already in the set

// Removal returns an Optional containing the removed element, or nil if not found
let removedElement = stringSet.remove("Banana")

// Removes all elements, optionally keeping the allocated capacity
stringSet.removeAll(keepingCapacity: true)
```

## Fundamental Set Operations

Swift provides built-in methods to perform mathematical set operations. These methods return a new `Set` and do not mutate the original collections.

```swift theme={"dark"}
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]

// Union: Elements in either set
let unionSet = setA.union(setB) 
// Result: [1, 2, 3, 4, 5, 6] (unordered)

// Intersection: Elements common to both sets
let intersectionSet = setA.intersection(setB) 
// Result: [3, 4]

// Subtracting: Elements in setA that are not in setB
let differenceSet = setA.subtracting(setB) 
// Result: [1, 2]

// Symmetric Difference: Elements in either set, but not both
let symmetricDiffSet = setA.symmetricDifference(setB) 
// Result: [1, 2, 5, 6]
```

*Note: Swift also provides mutating equivalents for these operations: `formUnion()`, `formIntersection()`, `subtract()`, and `formSymmetricDifference()`.*

## Set Comparison and Equality

Sets can be compared using standard equality operators or specific relational methods. Two sets are considered equal if they contain the exact same elements, regardless of internal memory order.

```swift theme={"dark"}
let setC: Set = [1, 2]

// Subset: All elements of setC are contained in setA
let isSubset = setC.isSubset(of: setA)               // true

// Superset: setA contains all elements of setC
let isSuperset = setA.isSuperset(of: setC)           // true

// Strict Subset/Superset: Subset/Superset, but the sets are not equal
let isStrictSubset = setC.isStrictSubset(of: setA)   // true

// Disjoint: The sets have no elements in common
let isDisjoint = setC.isDisjoint(with: setB)         // true
```

## Iteration

Because sets are unordered, iterating over a `Set` does not guarantee any specific sequence. To iterate in a predictable order, use the `sorted()` method, which returns an `Array` of the set's elements sorted by their `<` operator.

```swift theme={"dark"}
// Unordered iteration
for number in setA {
    print(number)
}

// Ordered iteration (returns an Array)
for number in setA.sorted() {
    print(number)
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
