How to check if a set contains a particular element in Swift
Overview
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.
Syntax
set.contains(element)
Syntax for checking if an element is contained in a set
Parameter value
element: This is the element whose presence we want to check for in our set instanceset.
Return value
Boolean: Thecontains()method returns aBooleanvalue. If the element exists, thentrueis returned. Otherwise,falseis returned.
Code example
// 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"))
Code explanation
- Lines 2–4: We create some set variables and initialize them with some elements.
- Lines 7–9: We use the
contains()method to check the set variables to see if they contain certain elements. Then, we print the results to the console.