Swift – Check if Set Contains Elements

In this tutorial, we will learn how to check if a Set contains an element.

To check if an element is present in a Set, use contains() method.

setName.contains(element)

Example 1 – Check if a number is present in a Set

In this Swift program, we take a set of prime numbers and check if the elements 5 and 6 are present in the Set.

main.swift

let primes: Set = [2, 3, 5, 7, 11, 13]

var isElementPresent = primes.contains(5)
print("Is element (5) present: \(isElementPresent)")

isElementPresent = primes.contains(6)
print("Is element (6) present: \(isElementPresent)")

Output

Is element (5) present: true
Is element (6) present: false
ADVERTISEMENT

Example 2 – Check if a String is present in a Set

In this Swift program, we take a set of month names and check if the elements “January” and “Sunday” are present in the Set.

main.swift

let months: Set = ["January", "February", "March"]

var isElementPresent = months.contains("January")
print("Is element (January) present: \(isElementPresent)")

isElementPresent = months.contains("Sunday")
print("Is element (Sunday) present: \(isElementPresent)")

Output

Is element (January) present: true
Is element (Sunday) present: false

Conclusion

In this Swift Tutorial, we have learned how to check if an element is present in the Set with the help of Swift example programs.