Subset and Superset
Part of the Logic & Flow section of Coddy's Swift journey — lesson 21 of 56.
Beyond combining sets, you can also compare them.
isSubset(of:) answers "is every one of my elements also in the other set?"
let small: Set = [1, 2]
let big: Set = [1, 2, 3, 4]
small.isSubset(of: big) // true
big.isSubset(of: small) // falseisSuperset(of:) is the reverse, "do I contain every element of the other set?":
big.isSuperset(of: small) // trueisDisjoint(with:) returns true when the two sets share no elements at all:
let evens: Set = [2, 4, 6]
let odds: Set = [1, 3, 5]
evens.isDisjoint(with: odds) // trueThese three predicates are the cleanest way to express "required permissions" or "all-of" / "none-of" rules without writing a manual loop.
Challenge
MediumYou're checking access for a document. Read three lines:
- The user's permissions (comma-separated)
- The required permissions (comma-separated)
- The forbidden permissions (comma-separated)
The user is granted access when:
- Their permissions are a superset of the required ones (every required permission is held)
- Their permissions are disjoint from the forbidden ones
Print exactly one of:
grantedmissing: <...>when required permissions are missing (sorted, comma-separated). Print this even if forbidden permissions are also held.forbidden: <...>when no required permissions are missing but forbidden ones are held (sorted, comma-separated)
For input read,write,admin / read,write / delete, the output is granted.
For input read / read,write / delete, the output is missing: write.
Cheat sheet
Set comparison methods in Swift:
let small: Set = [1, 2]
let big: Set = [1, 2, 3, 4]
small.isSubset(of: big) // true – every element of small is in big
big.isSuperset(of: small) // true – big contains every element of small
let evens: Set = [2, 4, 6]
let odds: Set = [1, 3, 5]
evens.isDisjoint(with: odds) // true – no shared elementsTry it yourself
let user = Set(readLine()!.components(separatedBy: ","))
let required = Set(readLine()!.components(separatedBy: ","))
let forbidden = Set(readLine()!.components(separatedBy: ","))
// TODO: granted | missing: ... | forbidden: ...
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