Bird
0
0

What is the output of the following Swift code?

medium📝 Predict Output Q13 of 15
Swift - Collections
What is the output of the following Swift code?
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]
let result = setA.subtracting(setB)
print(result.sorted())
A[5, 6]
B[3, 4]
C[1, 2]
D[1, 2, 3, 4, 5, 6]
Step-by-Step Solution
Solution:
  1. Step 1: Understand subtracting operation

    setA.subtracting(setB) returns elements in setA that are NOT in setB. Here, setA is [1,2,3,4], setB is [3,4,5,6].
  2. Step 2: Calculate difference

    Elements 3 and 4 are in both sets, so they are removed. Remaining elements in setA are 1 and 2.
  3. Final Answer:

    [1, 2] -> Option C
  4. Quick Check:

    subtracting = elements only in first set [OK]
Quick Trick: Subtracting removes elements found in second set from first [OK]
Common Mistakes:
  • Confusing subtracting with intersection
  • Expecting union instead of difference
  • Not sorting output before printing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes