.contains()

The .contains() method returns true if the given element exists in the set, false otherwise.

Syntax

setName.contains(element)

setName is the set being searched, and element is the element being searched for.

Example

The following is an example of the .contains() method:

let numberSet: Set = [1, 2, 3, 4]
let targetNumber = 2
if numberSet.contains(targetNumber) {
print("This set contains this number: \(targetNumber)")
} else {
print("This set does not contain this number: \(targetNumber)")
}

This example results in the following output:

This set contains this number: 2

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Swift on Codecademy

Contributors