Set membership and equality

It's easy to check whether a set is equal to the subset, superset, or disjoint of another set. Type in and run the following code:

// Set membership and equality
// movieGenres contains "Horror", "Romantic Comedy", "War"
// movieGenres2 contains "Science Fiction", "War", "Fantasy"
let movieGenresSubset: Set = ["Horror", "Romantic Comedy"]
let movieGenresSuperset: Set = ["Horror", "Romantic Comedy", "War",
"Science Fiction", "Fantasy"]
let movieGenresDisjoint: Set = ["Bollywood"]

movieGenres == movieGenres2
// false
movieGenresSubset.isSubset(of: movieGenres)
// true
movieGenresSuperset.isSuperset(of: movieGenres)
// true
movieGenresDisjoint.isDisjoint(with: movieGenres)
// true

Let's see how this code works:

  • The isEqual operator (==) checks whether all the members of one set are the same as those of another set. false will be displayed in the Results area.
  • isSubset(of:) checks whether a set is a subset of another set. true will be displayed in the Results area.
  • isSuperset(of:) checks whether a set is a superset of another set. true will be displayed in the Results area.
  • isDisjoint(of:) checks whether a set has no values in common with another set. true will be displayed in the Results area:

This concludes the section on sets.

To find out more about arrays, dictionaries, and sets, visit https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.196.184