I want to find out if an exact instance of an object is in an Array. This seemed like a pretty useful function to have, so I tried to make an extension of Array:
extension Array {
func containsIdenticalObject(object: AnyObject)->Bool {
if self.count > 0 {
for (_, objectToCompare) in self.enumerate() {
if object === objectToCompare {
return true
}
}
}
return false
}
}
I get the message:
error: binary operator '===' cannot be applied to operands of type 'AnyObject' and 'Element'.
I have tried jiggering it around with various generic modifications, such as <T: This>
and where Self: That
, but I always get the same message.
This seems like it should definitely be possible. How do I need to modify this function to make it work?
Edit
I have been able to make this work as a stand-alone function:
func arrayContainsExactInstance<T>(array:[T], _ object:T)->Bool {
if array.count > 0 {
for (_, givenObject) in array.enumerate() {
let givenObjectAsAnyObject = givenObject as! AnyObject
let targetObjectAsAnyObject = object as! AnyObject
if ObjectIdentifier(givenObjectAsAnyObject) == ObjectIdentifier(targetObjectAsAnyObject) {
return true
}
}
}
return false
}
...which is great, except a) it seems over-complicated, and b) there must be some way to add it to an actual extension...