Building on this question of mine (and the accepted answer), I want to test containment of a value in an array.
The value is stored in a variable defined as of type Any
, and the array is defined as [Any]
.
The actual types of the value stored in the variable and the elements in the array are decided at runtime, but are guaranteed to satisfy the following conditions:
- Both types (variable and array elements) coincide, and
- They are either one of
String
,Int
orBool
.
So far, I got this code working:
var isContained = false
if let intValue = anyValue as? Int {
isContained = arrayOfAny.contains({element in return ((element as? Int) == intValue)})
}
else if let stringValue = anyValue as? String {
isContained = arrayOfAny.contains({element in return ((element as? String) == stringValue)})
}
else if let boolValue = anyValue as? Bool {
isContained = arrayOfAny.contains({element in return ((element as? Bool) == boolValue)})
}
However, there is a lot of logic duplication and I wish I could make it smarter, perhaps something like this:
isContained = arrayOfAny.contains({element in
return ((element as? Equatable) == (anyValue as? Equatable))
})
...but the restrictions on the use of the protocol Equatable
stand in the way. Any advice?