Subtracting and Symmetric
Part of the Logic & Flow section of Coddy's Swift journey — lesson 20 of 56.
Two more set operations finish the toolkit.
subtracting returns the elements of the first set that are not in the second:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]
a.subtracting(b) // {1, 2}symmetricDifference returns the elements that are in exactly one of the two sets, never both:
a.symmetricDifference(b) // {1, 2, 5}Together with union and intersection, these four cover every set algebra question you'll meet day to day.
Set membership is also useful as a filter: ask whether a value lives in a set in O(1):
let stopwords: Set = ["the", "a", "an"]
let words = ["the", "cat", "sat", "on", "a", "mat"]
let real = words.filter { !stopwords.contains($0) }
// ["cat", "sat", "on", "mat"]Challenge
EasyRead two lines of input, each a comma-separated list of strings. Treat them as currentMembers and renewedMembers respectively.
Print three lines, each sorted alphabetically and joined with , (or empty when there are none):
Lapsed: <...>> current minus renewedNew: <...>> renewed minus currentStayed: <...>> intersection of the two
For input alice,bob,cara on line 1 and bob,cara,dan on line 2, the output is:
Lapsed: alice
New: dan
Stayed: bob,caraCheat sheet
subtracting returns elements in the first set not in the second:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]
a.subtracting(b) // {1, 2}symmetricDifference returns elements in exactly one of the two sets:
a.symmetricDifference(b) // {1, 2, 5}Use a set as an O(1) filter with contains:
let stopwords: Set = ["the", "a", "an"]
let words = ["the", "cat", "sat", "on", "a", "mat"]
let real = words.filter { !stopwords.contains($0) }
// ["cat", "sat", "on", "mat"]Try it yourself
let current = Set(readLine()!.components(separatedBy: ","))
let renewed = Set(readLine()!.components(separatedBy: ","))
// TODO: print Lapsed (current - renewed), New (renewed - current), Stayed (intersection)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check4Sets
Creating SetsUnion and IntersectionSubtracting and SymmetricSubset and SupersetRecap - Tag Filter