.contains()

chip4572880328's avatar
Published Sep 2, 2024
Contribute to Docs

The .contains() method returns true if an array contains a specified element, and false otherwise.

Syntax

dictionaryInstance.contains(element)
  • element: The item to check for in the array. It returns true if the item is present, and false otherwise.

To check if a dictionary contains a specific key-value pair, the following is used:

dictionaryInstance.contains{check}
  • check: A closure that takes a key-value pair (key, value) and returns true if the pair satisfies the specified condition, and false otherwise.

Example

In the example below, .contains() is checking if a particular actor is in an array storing a movie’s cast:

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon"))

This example results in the following output:

true

All contributors

Contribute to Docs

Learn Swift on Codecademy