Swift 3
Trying to write a generic array extension that gets all indexes of items that DON'T equal value
example
let arr: [String] = ["Empty", "Empty", "Full", "Empty", "Full"]
let result: [Int] = arr.indexes(ofItemsNotEqualTo item: "Empty")
//returns [2, 4]
I tried to make a generic function:
extension Array {
func indexes<T: Equatable>(ofItemsNotEqualTo item: T) -> [Int]? {
var result: [Int] = []
for (n, elem) in self.enumerated() {
if elem != item {
result.append(n)
}
}
return result.isEmpty ? nil : result
}
}
But that gives a warning: Binary operator cannot be applied to operands of type "Element" and "T".
So then I did this where I cast the element (note the as?)
extension Array {
func indexes<T: Equatable>(ofItemsNotEqualTo item: T) -> [Int]? {
var result: [Int] = []
for (n, elem) in self.enumerated() {
if elem as? T != item {
result.append(n)
}
}
return result.isEmpty ? nil : result
}
}
But now it seems the type checking has gone out the window, because if I pass in an integer I get the wrong result
let arr: [String] = ["Empty", "Empty", "Full", "Empty", "Full"]
let result: [Int] = arr.indexes(ofItemsNotEqualTo item: 100)
//returns [0, 1, 2, 3, 4]
Help would be greatly appreciated.
Is there a better way to do this with the reduce function?