Skip to content

Instantly share code, notes, and snippets.

@johankj
Created December 26, 2015 14:16
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 johankj/a8cc1bb1eaa6e08ba945 to your computer and use it in GitHub Desktop.
Save johankj/a8cc1bb1eaa6e08ba945 to your computer and use it in GitHub Desktop.
A GroupBy method in Swift as seen in other languages
extension SequenceType where Generator.Element: Comparable {
func group() -> [[Generator.Element]] {
return self.group { $0 == $1 }
}
func group(by groupBy: (Generator.Element, Generator.Element) -> Bool) -> [[Generator.Element]] {
return self.reduce([]) { (xs, q) -> [[Generator.Element]] in
guard xs.count > 0 else { return [[q]] }
var xs = xs
let last = xs.count-1
if groupBy(xs[last][0], q) {
xs[last].append(q)
return xs
}
xs.append([q])
return xs
}
}
}
["a", "a", "a", "A", "A", "b", "c", "b"].group() // [["a", "a", "a"], ["A", "A"], ["b"], ["c"], ["b"]]
["a", "a", "a", "A", "A", "b", "c", "b"].group { a, b in a.lowercaseString == b.lowercaseString } // [["a", "a", "a", "A", "A"], ["b"], ["c"], ["b"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment