Instance Method

contains(where:)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

Declaration

func contains(where predicate: (Int) throws -> Bool) rethrows -> Bool

Parameters

predicate

A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Return Value

true if the sequence contains an element that satisfies predicate; otherwise, false.

Discussion

You can use the predicate to check for an element of a type that doesn’t conform to the Equatable protocol, such as the HTTPResponse enumeration in this example.

enum HTTPResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        return true
    } else {
        return false
    }
}
// 'hadError' == true

Alternatively, a predicate can be satisfied by a range of Equatable elements or a general condition. This example shows how you can check an array for an expense greater than $100.

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
// 'hasBigPurchase' == true

Complexity: O(n), where n is the length of the sequence.

See Also

Testing Set Membership

func contains(IndexSet.Element) -> Bool

Returns true if self contains integer.

func contains(integersIn: IndexSet) -> Bool

Returns true if self contains all of the integers in indexSet.

func contains(integersIn: Range<IndexSet.Element>) -> Bool

Returns true if self contains all of the integers in range.

func intersects(integersIn: Range<IndexSet.Element>) -> Bool

Returns true if self intersects any of the integers in range.

func starts<PossiblePrefix>(with: PossiblePrefix) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

func isDisjoint(with: IndexSet) -> Bool

Returns a Boolean value that indicates whether the set has no members in common with the given set.

func isStrictSubset(of: IndexSet) -> Bool

Returns a Boolean value that indicates whether this set is a strict subset of the given set.

func isStrictSuperset(of: IndexSet) -> Bool

Returns a Boolean value that indicates whether this set is a strict superset of the given set.

func isSubset(of: IndexSet) -> Bool

Returns a Boolean value that indicates whether the set is a subset of another set.

func isSuperset(of: IndexSet) -> Bool

Returns a Boolean value that indicates whether the set is a superset of the given set.