Swift .contains()
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 returnstrueif the item is present, andfalseotherwise.
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 returnstrueif the pair satisfies the specified condition, andfalseotherwise.
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
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours