A set is an unordered collection of elements or values that are unique. We can check if a set in Swift contains a particular element by using the contains()
method.
set.contains(element)
element
: This is the element whose presence we want to check for in our set instance set
.Boolean
: The contains()
method returns a Boolean
value. If the element exists, then true
is returned. Otherwise, false
is returned.// create some Set instanceslet alphabets: Set = ["A", "B", "C", "D"]let numbers: Set = [1, 2, 3, 4, 5]let vehicles: Set = ["Ford", "SUV", "Porsche"]// check if some elements existsprint(alphabets.contains("X")) // falseprint(numbers.contains(2))print(vehicles.contains("Ford"))
contains()
method to check the set variables to see if they contain certain elements. Then, we print the results to the console.