Skip to content

Instantly share code, notes, and snippets.

@perlmunger
Last active April 27, 2016 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perlmunger/a5debf841099404cb02678a5e2f368b9 to your computer and use it in GitHub Desktop.
Save perlmunger/a5debf841099404cb02678a5e2f368b9 to your computer and use it in GitHub Desktop.
Show how to add a mutating function for RangeReplaceableCollectionType that appends items only if they are not already in the collection.
extension RangeReplaceableCollectionType where Generator.Element : Equatable {
mutating func appendDistinct(object : Generator.Element) {
if !self.contains(object) {
self.append(object)
}
}
}
// A derivative solution using filter instead of contains
extension RangeReplaceableCollectionType where Generator.Element : Equatable {
mutating func appendDistinct(object : Generator.Element) {
let filtered = self.filter( { $0 == object } )
if filtered.first == nil {
self.append(object)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment