0

With an Array as Any object:

var a : [Any] = []
 let x : String = "This is X"
 let y : Int = 9
 let z : [Any] = ["1", "no. 2"]

 a.append(x)
 a.append(y)
 a.append(z)

let ele1 = 9
let ele2 = "This is test string"

Very simple if the a is String/Int array, but this is Any array! How to check ele1, ele2 exists or not in a?

0

2 Answers 2

3

Since Any does not conform to Equatable, [Any] does not have a contains(_:) method. You cannot use == to compare Anys either.

However, [Any] does have a contains(where:) method that accepts a predicate. You can pass in a (Any) -> Bool and if there is anything in the array that makes the closure return true, contains returns true.

We can use contains(where:) to do exactly what you want. For example, if you want to check for ele2:

a.contains(where: { ($0 as? String) == ele2 })

What I did is that I casted the element to string first, then use ==.

You can also create an extension that does this:

extension Array where Element == Any {
    func contains<T: Equatable>(_ element: T) -> Bool {
        return contains(where: { ($0 as? T) == element })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you could try something like this:

a.forEach({
    if let testInt: Int  = $0 as? Int, ele1 == testInt {
        print("found")
    }
})

And similar for any other types. I'm away from my computer so haven't tested the above, but I think it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.