Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Last active August 15, 2017 16:37
Show Gist options
  • Select an option

  • Save vukcevich/591b49f38bb77402e8510e367c5d0842 to your computer and use it in GitHub Desktop.

Select an option

Save vukcevich/591b49f38bb77402e8510e367c5d0842 to your computer and use it in GitHub Desktop.
Remove duplicate objects in an array - Hashable, CustomStringConvertible
//Reference:
//https://stackoverflow.com/questions/34709066/remove-duplicate-objects-in-an-array
//https://medium.com/@YogevSitton/use-auto-describing-objects-with-customstringconvertible-49528b55f446
func uniq<S: Sequence, E: Hashable>(_ source: S) -> [E] where E == S.Iterator.Element {
var seen = Set<E>()
return source.filter { seen.update(with: $0) == nil }
}
struct Post : Hashable, CustomStringConvertible {
var id : Int
var hashValue : Int { return self.id }
//Using Swift’s reflection capabilities we print the class’ name, iterate through the properties and print their values.
var description: String {
// return "\(hashValue)" //"\(id)"
var description = "\(type(of: self))]-"
let selfMirror = Mirror(reflecting:self)
for child in selfMirror.children {
if let propertyName = child.label {
description += "\(propertyName): \(child.value)"
}
}
return description
}
}
func == (lhs: Post, rhs: Post) -> Bool {
return lhs.id == rhs.id
}
var posts : [Post] = [Post(id: 1), Post(id: 7), Post(id: 2), Post(id: 1), Post(id: 3), Post(id: 5), Post(id: 7), Post(id: 9)]
print(posts)
/* [Post(id: 1), Post(id: 7), Post(id: 2), Post(id: 1), Post(id: 3), Post(id: 5), Post(id: 7), Post(id: 9)] */
var myUniquePosts = uniq(posts)
print(myUniquePosts)
/* [Post(id: 1), Post(id: 7), Post(id: 2), Post(id: 3), Post(id: 5), Post(id: 9)] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment