0
0
Swiftprogramming~30 mins

Set algebra (union, intersection, difference) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Set algebra (union, intersection, difference)
📖 Scenario: You are organizing two groups of friends who like different sports. You want to find out who likes either sport, who likes both, and who likes only one of the sports.
🎯 Goal: Build a Swift program that uses sets to find the union, intersection, and difference of two groups of friends.
📋 What You'll Learn
Create two sets of strings representing friends who like basketball and soccer.
Create a variable to hold the union of both sets.
Create a variable to hold the intersection of both sets.
Create a variable to hold the difference of basketball friends who do not like soccer.
Print the results clearly.
💡 Why This Matters
🌍 Real World
Sets help manage groups of items or people, like customers, tags, or preferences, without duplicates.
💼 Career
Understanding set operations is useful in data processing, filtering, and combining information efficiently in software development.
Progress0 / 4 steps
1
Create two sets of friends
Create two sets called basketballFans and soccerFans with these exact values: basketballFans contains "Alice", "Bob", "Charlie" and soccerFans contains "Bob", "Diana", "Eve".
Swift
Need a hint?

Use let to create sets with square brackets and commas separating names.

2
Create variables for union, intersection, and difference
Create three variables called allFans, bothFans, and onlyBasketballFans. Set allFans to the union of basketballFans and soccerFans. Set bothFans to the intersection of basketballFans and soccerFans. Set onlyBasketballFans to the difference of basketballFans minus soccerFans.
Swift
Need a hint?

Use .union(), .intersection(), and .subtracting() methods on sets.

3
Print the results
Write three print statements to display the contents of allFans, bothFans, and onlyBasketballFans with clear labels.
Swift
Need a hint?

Use print with string interpolation and .sorted() to show sets in order.

4
Run the program and see the output
Run the program to display the sets of fans with their labels exactly as printed by the print statements.
Swift
Need a hint?

Check the console output matches exactly the printed lines with sorted arrays.