Challenge - 5 Problems
Swift Set Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using sets?
Consider the following Swift code that creates and manipulates sets. What will be printed?
Swift
let setA: Set<Int> = [1, 2, 3, 4] let setB: Set<Int> = [3, 4, 5, 6] let unionSet = setA.union(setB) print(unionSet.sorted())
Attempts:
2 left
💡 Hint
Think about what the union operation does to two sets.
✗ Incorrect
The union of two sets combines all unique elements from both sets. Here, setA and setB combined have elements 1, 2, 3, 4, 5, and 6. Sorting them gives [1, 2, 3, 4, 5, 6].
❓ Predict Output
intermediate2:00remaining
What does this Swift code print after set intersection?
Look at this Swift code that finds the intersection of two sets. What is the output?
Swift
let setX: Set<Int> = [10, 20, 30, 40] let setY: Set<Int> = [30, 40, 50, 60] let intersectionSet = setX.intersection(setY) print(intersectionSet.sorted())
Attempts:
2 left
💡 Hint
Intersection returns only elements common to both sets.
✗ Incorrect
The intersection of setX and setY contains elements present in both sets, which are 30 and 40. Sorting them results in [30, 40].
❓ Predict Output
advanced2:00remaining
What is the output of this Swift code using symmetricDifference?
This Swift code uses symmetricDifference on two sets. What will be printed?
Swift
let set1: Set<Int> = [1, 2, 3, 4, 5] let set2: Set<Int> = [4, 5, 6, 7] let symDiff = set1.symmetricDifference(set2) print(symDiff.sorted())
Attempts:
2 left
💡 Hint
Symmetric difference returns elements in either set but not in both.
✗ Incorrect
The symmetric difference excludes elements common to both sets (4 and 5). So the result is [1, 2, 3, 6, 7].
❓ Predict Output
advanced2:00remaining
What is the count of elements after subtracting sets in Swift?
Given these two sets, what is the count of elements in the result after subtracting setB from setA?
Swift
let setA: Set<Int> = [100, 200, 300, 400, 500] let setB: Set<Int> = [300, 400, 600] let differenceSet = setA.subtracting(setB) print(differenceSet.count)
Attempts:
2 left
💡 Hint
Subtracting removes elements of setB from setA.
✗ Incorrect
Elements 300 and 400 are removed from setA. Remaining elements are 100, 200, and 500, so count is 3.
🧠 Conceptual
expert3:00remaining
Which Swift set operation produces this output?
You have two sets: setM = [2, 4, 6, 8] and setN = [1, 2, 3, 4]. Which operation on setM and setN produces the output [1, 3, 6, 8] when sorted?
Attempts:
2 left
💡 Hint
Think about how union, intersection, and subtracting combine to form symmetric difference.
✗ Incorrect
Option A computes union minus intersection, which is the symmetric difference. The output is [1, 3, 6, 8].