Last active
April 27, 2016 15:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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