Concept Flow - Set creation and operations
Start
Create Set
Add Elements
Perform Operations
Union
Use Results
End
Start by creating a set, add elements, then perform operations like union, intersection, and difference to get new sets.
var setA: Set<Int> = [1, 2, 3] let setB: Set<Int> = [3, 4, 5] let unionSet = setA.union(setB) let intersectSet = setA.intersection(setB) let diffSet = setA.subtracting(setB)
| Step | Action | SetA | SetB | Result Variable | Result Value |
|---|---|---|---|---|---|
| 1 | Create setA | [1, 2, 3] | [] | ||
| 2 | Create setB | [1, 2, 3] | [3, 4, 5] | ||
| 3 | Union setA ∪ setB | [1, 2, 3] | [3, 4, 5] | unionSet | [1, 2, 3, 4, 5] |
| 4 | Intersection setA ∩ setB | [1, 2, 3] | [3, 4, 5] | intersectSet | [3] |
| 5 | Difference setA - setB | [1, 2, 3] | [3, 4, 5] | diffSet | [1, 2] |
| 6 | End of operations | [1, 2, 3] | [3, 4, 5] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|---|---|
| setA | empty | [1, 2, 3] | [1, 2, 3] | [1, 2, 3] | [1, 2, 3] | [1, 2, 3] | [1, 2, 3] |
| setB | empty | empty | [3, 4, 5] | [3, 4, 5] | [3, 4, 5] | [3, 4, 5] | [3, 4, 5] |
| unionSet | undefined | undefined | undefined | [1, 2, 3, 4, 5] | [1, 2, 3, 4, 5] | [1, 2, 3, 4, 5] | [1, 2, 3, 4, 5] |
| intersectSet | undefined | undefined | undefined | undefined | [3] | [3] | [3] |
| diffSet | undefined | undefined | undefined | undefined | undefined | [1, 2] | [1, 2] |
Set creation: var setA: Set<Int> = [elements] Operations: - union: combines unique elements - intersection: common elements - difference: elements in first set not in second Sets hold unique values only.
Set in Swift?Set<Int> = [1, 2, 3, 4]. Others have syntax errors or wrong casting.let setA: Set<Int> = [1, 2, 3, 4]
let setB: Set<Int> = [3, 4, 5, 6]
let result = setA.intersection(setB)
print(result.sorted())
var fruits: Set<String> = ["apple", "banana", "orange"]
fruits.append("grape")
insert() to add elements, not append().append() on a Set causes a compile error because it is not defined for Set.let setX: Set<Int> = [1, 2, 3, 4, 5]
let setY: Set<Int> = [4, 5, 6, 7]
setX or setY but not in both?Pass the test and this pattern moves unknown