Swift Array contains()

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


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

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

contains() Syntax

The syntax of the array contains() method is:


Here, array is an object of the Array class.

contains() Parameters

The contains() method takes a single parameter:

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

contains() Return Values

The contains() method returns:

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

Example 1: Swift String contains()

var names = ["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 array, so the method returns true.
  • "Federer" is not present in the array, so the method returns false.

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

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

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


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