Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Check whethere an array contain element

I wonder why following not working:

var tmp = [AnyObject] ()
for (key, value) in dictionary{

        if (tmp.contains(value)){

        } 
      tmp.append(value as AnyObject)
    }

Look like there is no method .contain for an Array. it force me to use some other method tmp.contains(where: <#T##(AnyObject) throws -> Bool#>)

But i dont want to. I simply want to check whether an array contain that specific object!

Upvotes: 0

Views: 136

Answers (2)

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

I recommend switching from AnyObject to AnyHashable(of course if that's possible), because AnyHashable is Equatable. Your code would look like this:

var tmp = [AnyHashable]()
var dictionary: [Int: Any] = [1: "Hello1", 2: "Hello2", 3: "Hello3", 4: false, 5: 289 ]
for (key, value) in dictionary{
    if tmp.contains(value as! AnyHashable){
         continue
    }
    tmp.append(value as! AnyHashable)
}

Hope it helps!

Upvotes: 1

DrummerB
DrummerB

Reputation: 40211

That's because AnyObject is not an Equatable object. If you have an AnyObject array, you have to do the comparisons yourself. If you used an array of Strings or a custom class for instance you could use this contains() method of Sequence

Upvotes: 1

Related Questions