Skip to content

Instantly share code, notes, and snippets.

@marty-suzuki
Last active December 25, 2016 02:32
Show Gist options
  • Save marty-suzuki/f0d501c84cf767912d31fcbbfd4e6e8d to your computer and use it in GitHub Desktop.
Save marty-suzuki/f0d501c84cf767912d31fcbbfd4e6e8d to your computer and use it in GitHub Desktop.
extension Array {
func unique(predicate: (Element, Element) -> Bool) -> [Element] {
var result: [Element] = []
forEach { e -> Void in
guard !result.contains({ r -> Bool in
return predicate(r, e)
}) else { return }
result.append(e)
}
return result
}
}
//Usage
/*
class Post {
let id: Int
let text: String
init(id: Int, text: String) {
self.id = id
self.text = text
}
}
let posts = (0...100).flatMap { Post(id: $0, text: "text\($0)") } + (20...50).flatMap { Post(id: $0, text: "text\($0)") } //132 items
let uniquePosts = posts.unique { $0.id == $1.id } //101 items
*/
@hanishassim
Copy link

the syntax not updated to the current swift version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment