0
0
Swiftprogramming~10 mins

Set algebra (union, intersection, difference) in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to find the union of two sets.

Swift
let setA: Set<Int> = [1, 2, 3]
let setB: Set<Int> = [3, 4, 5]
let unionSet = setA.[1](setB)
print(unionSet.sorted())
Drag options to blanks, or click blank then click option'
Aunion
B-
Cintersect
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' operator which is not defined for sets in Swift.
Using 'intersect' which finds common elements.
2fill in blank
medium

Complete the code to find the intersection of two sets.

Swift
let setX: Set<String> = ["apple", "banana", "cherry"]
let setY: Set<String> = ["banana", "date", "fig"]
let commonFruits = setX.[1](setY)
print(commonFruits.sorted())
Drag options to blanks, or click blank then click option'
Aintersect
Bunion
Cintersection
Dsubtract
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'union' which combines all elements.
Using 'subtract' which removes elements.
3fill in blank
hard

Fix the error in the code to find the difference between two sets.

Swift
let set1: Set<Int> = [10, 20, 30, 40]
let set2: Set<Int> = [30, 40, 50]
let diffSet = set1.[1](set2)
print(diffSet.sorted())
Drag options to blanks, or click blank then click option'
Asubtract
Bdifference
Csubtracting
Ddiff
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'subtract' which is a mutating method, not returning a new set.
Using incorrect method names like 'diff'.
4fill in blank
hard

Fill both blanks to create a set of fruits that are in setA but not in setB.

Swift
let setA: Set<String> = ["orange", "apple", "banana"]
let setB: Set<String> = ["banana", "kiwi"]
let result = setA.[1](setB)
print(result.[2]())
Drag options to blanks, or click blank then click option'
Asubtracting
Bsorted
Cdifference
DsortedDescending
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'difference' which is not a valid method.
Using 'sortedDescending' which sorts in reverse order.
5fill in blank
hard

Fill all three blanks to create a dictionary with fruit names as keys (uppercase) and their counts as values, only for fruits with count greater than 1.

Swift
let fruits = ["apple", "banana", "apple", "cherry", "banana", "banana"]
let counts = Dictionary(grouping: fruits, by: [1]).mapValues { $0.count }
let filtered = counts.filter { $0.value [2] 1 }
let result = filtered.mapKeys { [3] }
print(result)
Drag options to blanks, or click blank then click option'
A{ $0 }
B>
C{ $0.uppercased() }
D{ $0.lowercased() }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong grouping key.
Using wrong comparison operator.
Not converting keys to uppercase.