BadmintonCat BadmintonCat - 3 years ago 207
Swift Question

Array containsObject() extension

I'm currently using this extension:

extension Array
{
func containsObject(_ object:Any) -> Bool
{
if let anObject:AnyObject = object as? AnyObject
{
for obj in self
{
if let anObj:AnyObject = obj as? AnyObject
{
if anObj === anObject
{
return true
}
}
}
}
return false
}
}


I know this is sub-optimal. And it also generates some unnecessary compile-time warnings:


Conditional cast from 'Any' to 'AnyObject' always succeeds.

Conditional cast from 'Element' to 'AnyObject' always succeeds.


Can somebody suggest a better extension for checking containment of any kind of object?

Answer Source

That means there is no need to use conditional cast. Remove the if let and change as? to as

extension Array {
    func containsObject(_ object: Any) -> Bool {
        for obj in self {
            if obj as AnyObject === object as AnyObject {
                return true
            }
        }
        return false
    }
}

Or simply:

extension Array {
    func containsObject(_ object: Any) -> Bool {
        return contains(where: {$0 as AnyObject === object as AnyObject})
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download