Swift Set contains()

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

Example

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:

set.contains(obj)

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")
print(result)

Output

true
false

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) }

Output

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

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges