Swift Set contains()

In this tutorial, we will learn about the Swift Set contains() method with the help of examples.

The contains() method checks whether the specified element is present in the set or not.


var languages: Set = ["Swift", "C", "Java"]

// check if languages contains "Swift" var result = languages.contains("Swift")
print(result) // Output: true

contains() Syntax

The syntax of the set contains() method is:


Here, set is an object of the set class.

contains() Parameters

The contains() method takes a single parameter:

  • obj - element to be checked for its presence in the set

contains() Return Values

The contains() method returns:

  • true - if the set contains the specified element
  • false - if the set doesn't contain the specified element

Example 1: Swift String contains()

var names: Set = ["Gregory", "Perry", "Nadal"]

// check if names contains "Nadal"
var result = names.contains("Nadal")
print(result) // check if message contains "Federer"
result = names.contains("Federer")



In the above example,

  • "Nadal" is present in the set, so the method returns true.
  • "Federer" is not present in the set, so the method returns false.

Example 2: Using contains() With if...else

var names: Set = ["Gregory", "Perry", "Nadal"]
var name1 = "Gregory"
var name2 = "gregory"

// true because names contains "Gregory" if (names.contains(name1)) {
print( "set contains", name1) } else { print("set doesn't contain", name1) }
// contains() is case-sensitive // false because names doesn't contains "gregory" if (names.contains(name2)) {
print( "set contains", name2) } else { print( "set doesn't contain", name2) }


set contains Gregory
set doesn't contain gregory
Did you find this article helpful?