To check if a specific item is present in a Set in Swift, you can use the contains
method of the Set
class.
In this example,
Set
named numbers
and initialize it with some integer elements.itemToCheck
with the value of the item we want to check for.contains
method of the numbers
set to check if itemToCheck
is present in the set.contains
method returns a boolean value: true
if the item is present, and false
if it is not.import Foundation
let numbers: Set<Int> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let itemToCheck = 5
let containsItem = numbers.contains(itemToCheck)
print("Does the set contain \(itemToCheck)? \(containsItem)")
Does the set contain 5? true
In this example,
Set
named fruits
and initialize it with some string elements.itemToCheck
with the value of the item we want to check for.contains
method of the fruits
set to check if itemToCheck
is present in the set.contains
method returns a boolean value: true
if the item is present, and false
if it is not.import Foundation
let fruits: Set<String> = ["apple", "banana", "cherry", "date", "fig"]
let itemToCheck = "cherry"
let containsItem = fruits.contains(itemToCheck)
print("Does the set contain '\(itemToCheck)'? \(containsItem)")
Does the set contain 'cherry'? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in Swift language with well detailed examples.