In addition to set manipulation methods, there are a number of methods we can use to determine information about set membership.
The isSubset method will return true if all the elements in the set that the method is called on are contained within the set that's passed as a parameter:
print(mammals.isSubset(of: animalKingdom)) // true
The following diagram depicts Set B as the subset of Set A:
This will also return true if the two sets are equal (they contain the same elements). If you only want a true value if the set that the method is called on is a subset and not equal, then you can use isStrictSubset:
print(vertebrates.isStrictSubset(of: animalKingdom)) // false
print(mammals.isStrictSubset(of: animalKingdom)) // true
The isSuperset method will return true if all the elements in the set that have been passed as a parameter are within the set that the method is called on:
print(mammals.isSuperset(of: catFamily)) // true
The following diagram depicts Set A as the superset of Set B:
This will also return true if the two sets are equal (they contain the same elements). If you only want a true value if the set that the method is called on is a superset and not equal, then you can use isStrictSuperset:
print(animalKingdom.isStrictSuperset(of: vertebrates)) // false
print(animalKingdom.isStrictSuperset(of: domesticAnimals)) // true
The isDisjoint method will return true if there are no common elements between the set that the method is called on and the set that was passed as a parameter:
print(catFamily.isDisjoint(with: reptile)) // true
The following diagram shows that Set A and Set B are disjoint:
As with arrays, a set can be declared immutable by assigning it to a let constant instead of a var variable:
let planets: Set<String> = ["Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"]
planets.remove("Pluto") // Doesn't compile
This is because a set, like the other collection types, is a value type. Removing an element would mutate the set, which creates a new copy, but a let constant can't have a new value assigned to it, so the compiler prevents any mutating operations.