Bird
0
0

What is the output of the following Swift code?

medium📝 Predict Output Q4 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.union(setB)
print(result.sorted())
A[1, 2, 3, 4]
B[1, 2, 3, 4, 5, 6]
C[3, 4, 5, 6]
D[1, 2]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the union operation on setA and setB

    Union combines all unique elements from both sets: 1, 2, 3, 4, 5, 6.
  2. Step 2: Sorting the result

    The sorted() method returns the elements in ascending order: [1, 2, 3, 4, 5, 6].
  3. Final Answer:

    [1, 2, 3, 4, 5, 6] -> Option B
  4. Quick Check:

    Union result sorted = [1, 2, 3, 4, 5, 6] [OK]
Quick Trick: Union merges all unique elements; sort to see ordered list [OK]
Common Mistakes:
  • Confusing union with intersection
  • Forgetting to sort output
  • Expecting only elements from one set

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes