Grouping array in Swift

- 1 min
// For exactly reference to only one value when accessing by Dictionany. Normally, the return type is the value type
class Box<A> {
    var value: A
    init(_ val: A) {
        self.value = val
    }
}

public extension Sequence {
    func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
        var categories: [U: Box<[Iterator.Element]>] = [:]
        for element in self {
            let key = key(element)
            if case nil = categories[key]?.value.append(element) {
                categories[key] = Box([element])
            }
        }
        var result: [U: [Iterator.Element]] = Dictionary(minimumCapacity: categories.count)
        for (key,val) in categories {
            result[key] = val.value
        }
        return result
    }
}

struct People {
    let name:String
    let age:Int
}

let people = [ People(name: "Chung", age: 28), People(name: "Hieu", age: 24), People(name: "Bun Chu", age: 28) ,People(name: "Zun", age: 24)]

let groupByAge = people.group { $0.age }

Referential Definition:

  1. Sequence in Swift - Array type
  2. IteratorProtocol - Custom for for-in loop
  3. Optional Pattern - if case
  4. Dictionary - minimumCapacity
comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora