How to remove duplicates based on property in array in Swift

Issue #441

Make object conform to Equatable and Hashable and use Set to eliminate duplications. Set loses order so we need to sort after uniquing

1
2
3
4
5
6
7
8
9
10
11
12
13
struct App: Equatable, Hashable {
static func == (lhs: App, rhs: App) -> Bool {
return lhs.name == rhs.name && lhs.bundleId == rhs.bundleId
}

func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(bundleId)
}
}

let uniqueApps = Array(Set(unsortedApps))
let apps = uniqueApps.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

Comments