Array tricks - eonist/my-swift-projects GitHub Wiki
Removes all duplicates of Type A
protocol X{}
struct A:X{}
struct B:X{}
var arr:[X] = [A(),B(),B(),A(),A()]
func removeDups<T>(_ arr:[T], _ condition:(_ a:T, _ b:T)->Bool)->[T]{
var result:[T] = []
arr.forEach{ item in
if result.first(where:{condition(item,$0)}) == nil {result.append(item)}//append if doesn't exists
}
return result
}
let result = removeDups(arr, {type(of: $0) == type(of: $1) && $1 is A})
Swift.print("result: \(result)")//A,B,B