Last active
December 25, 2016 02:32
-
-
Save marty-suzuki/f0d501c84cf767912d31fcbbfd4e6e8d to your computer and use it in GitHub Desktop.
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 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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the syntax not updated to the current swift version