Sling Academy
Home/Swift/Swift: Checking if a Set Contains a Specific Element

Swift: Checking if a Set Contains a Specific Element

Last updated: May 09, 2023

In Swift, you can check whether a set contains a specific element or not by using the contains() method. Its syntax is as follows:

set.contains(element)

Where set is the name of the set you want to check and element is the value you want to look for. The method returns a Boolean value of true or false.

Example:

let mySet: Set<String> = ["Sling", "Academy", "Swift", "iOS"]

// check if mySet contains "Swift"
if mySet.contains("Swift") {
    print("mySet contains 'Swift'")
} else {
    print("mySet does not contain 'Swift'")
}

Output:

mySet contains 'Swift'

This succinct tutorial ends here. Happy coding!

Next Article: Iterating over a Set in Swift

Previous Article: Swift: Counting the Number of Elements in a Set

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array