A set stores elements or values that are unique. We can create a set of prime numbers and check if they are a subset of a particular range. A range is a series of values between a lower and an upper bound. When we specify a range, the lower bound is included within the range but the upper bound is excluded. For example, a range of 0–5 includes 0, 1, 2, 3, and 4.
To check if a set is a subset of a range, we use the isSubset(of:)
method of the set class.
set.isSubset(of: range)
range: This is the range of values we specify.
The value returned is a Boolean. A true
will be returned if the set is actually a subset. Otherwise, a false
will be returned.
// create some set instances and initializelet evenNumbers : Set = [2, 4, 6, 8]let primeNumbers : Set = [2, 3, 5, 7]// check if they are subset of a rangeprint(evenNumbers.isSubset(of: 0 ..< 10)) // trueprint(primeNumbers.isSubset(of: 0 ..< 5)) // false
isSubset(of:)
method to check if the set evenNumbers
, which contains even numbers from 2 to 8, is a subset of the range of numbers from 0 to 10, and print the result.isSubset(of:)
method, we check if primeNumbers
, which is a set of prime numbers from 2–7, is a subset of the range of values from 0 to 5, and print the result to the console.