Menu
Coddy logo textTech

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)            // false

isSuperset(of:) is the reverse, "do I contain every element of the other set?":

big.isSuperset(of: small)          // true

isDisjoint(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)       // true

These three predicates are the cleanest way to express "required permissions" or "all-of" / "none-of" rules without writing a manual loop.

challenge icon

Challenge

Medium

You're checking access for a document. Read three lines:

  1. The user's permissions (comma-separated)
  2. The required permissions (comma-separated)
  3. 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:

  • granted
  • missing: <...> 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 elements

Try it yourself

let user = Set(readLine()!.components(separatedBy: ","))
let required = Set(readLine()!.components(separatedBy: ","))
let forbidden = Set(readLine()!.components(separatedBy: ","))

// TODO: granted | missing: ... | forbidden: ...
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow