bearacuda13
bearacuda13

Reputation: 1854

Check if array contains something - Swift 4

I've found the .contains(Element) method pretty essential in my minimal experience writing Swift code, and have quickly realized that Apple changed it...

func contains(check:[[[Int]]], forElement: [[Int]]) -> Bool {
    for element in check {
        if areEqual(element, forElement) {
            return true
        }
    }
    return false
}
func areEqual(_ a:[[Int]], _ b:[[Int]]) -> Bool {
    for i in 0..<a.count {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

I've been messing with some large arrays, so I fixed my problem with that clunky function.

What happened?

How do you use the new way?

The example there is well over my head.

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

Upvotes: 10

Views: 25526

Answers (2)

ruiaureliano
ruiaureliano

Reputation: 1562

How about using this

let numbers = [1, 2, 3, 4]
let contains = numbers.contains(where: { $0 == 3 })
//contains == true

Or

let strings = ["A", "B", "C", "D"]
let contains = strings.contains(where: { $0 == "B" })
//contains == true

Even with other objects like NSColor

let colors: [NSColor] = [.red, .blue, .green]
contains = colors.contains(where: { $0 == .red })
//contains == true

Upvotes: 32

Dima
Dima

Reputation: 23624

That API just lets you pass a block where you can perform any checks you want. You can check whether the given element is equal to something, or whether its properties satisfy some constraints (such as in the example in the documentation). You should be able to perform a basic equality check like this:

func contains(check:[[[Int]]], forElement: [[Int]]) -> Bool {
    return check.contains { element in
        return areEqual(element, forElement)
    }
}

func areEqual(_ a:[[Int]], _ b:[[Int]]) -> Bool {
    for i in 0..<a.count {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

The contains block iterates over every element and returns either true or false. In the end, a single true for any element will return true for the whole function.

Upvotes: 3

Related Questions