Bird
0
0

Given two sets of integers:

hard📝 Application Q15 of 15
Swift - Collections
Given two sets of integers:
let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [1, 2, 3, 4, 5]
Write Swift code to find elements that are in either set but NOT in both (symmetric difference). What is the correct way to do this?
AAll of the above
Blet result = set1.symmetricDifference(set2)
Clet result = set1.subtracting(set2).union(set2.subtracting(set1))
Dlet result = set1.union(set2).subtracting(set1.intersection(set2))
Step-by-Step Solution
Solution:
  1. Step 1: Understand symmetric difference

    Symmetric difference means elements in either set but not in both.
  2. Step 2: Analyze each option

    let result = set1.symmetricDifference(set2) uses built-in symmetricDifference() method. let result = set1.union(set2).subtracting(set1.intersection(set2)) finds union then removes intersection, which equals symmetric difference. let result = set1.subtracting(set2).union(set2.subtracting(set1)) finds difference both ways then unions them, also symmetric difference.
  3. Step 3: Confirm all options produce same result

    All three approaches correctly compute symmetric difference.
  4. Final Answer:

    All of the above -> Option A
  5. Quick Check:

    Multiple ways to get symmetric difference [OK]
Quick Trick: Symmetric difference = union minus intersection or use built-in method [OK]
Common Mistakes:
  • Using only union or intersection alone
  • Confusing difference with symmetric difference
  • Not combining differences both ways

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes