Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
contains
set
communitycreator

How to check if a set contains a particular element in Swift

Theodore Kelechukwu Onyejiaku

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"))
Check if a certain element is contained in a set

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.

RELATED TAGS

swift
contains
set
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring