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 instance set.

Return value

  • Boolean: The contains() method returns a Boolean value. If the element exists, then true is returned. Otherwise, false is returned.

Code example

// create some Set instances
let alphabets: Set = ["A", "B", "C", "D"]
let numbers: Set = [1, 2, 3, 4, 5]
let vehicles: Set = ["Ford", "SUV", "Porsche"]
// check if some elements exists
print(alphabets.contains("X")) // false
print(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.

Free Resources