Bird
0
0

You have two Sets:

hard📝 Application Q8 of 15
Swift - Collections
You have two Sets:
let set1: Set = [1, 2, 3, 4, 5]
let set2: Set = [4, 5, 6, 7, 8]

Write Swift code to find elements in set1 that are not in set2 and sort them.
Alet diff = set1.intersection(set2).sorted()
Blet diff = set1.union(set2).sorted()
Clet diff = set1.subtracting(set2).sorted()
Dlet diff = set2.subtracting(set1).sorted()
Step-by-Step Solution
Solution:
  1. Step 1: Identify operation for elements in set1 not in set2

    subtracting() returns elements in the first Set that are not in the second.
  2. Step 2: Apply subtracting and sort

    set1.subtracting(set2) gives {1, 2, 3}. Sorting results in [1, 2, 3].
  3. Final Answer:

    let diff = set1.subtracting(set2).sorted() -> Option C
  4. Quick Check:

    Use subtracting() for difference between Sets [OK]
Quick Trick: Use subtracting() to find difference between Sets [OK]
Common Mistakes:
  • Using union() instead of subtracting()
  • Confusing intersection with difference
  • Reversing the order of subtracting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes