如果我们有这样的结构
struct Box { let name: String let thingsInside: Int }
和一系列 Box(es)
let boxes = [ Box(name: "Box 0", thingsInside: 1), Box(name: "Box 1", thingsInside: 2), Box(name: "Box 2", thingsInside: 3), Box(name: "Box 3", thingsInside: 1), Box(name: "Box 4", thingsInside: 2), Box(name: "Box 5", thingsInside: 3), Box(name: "Box 6", thingsInside: 1) ]
我们可以按thingsInside属性对这些框进行分组,以获取,Dictionary其中key是事物的数量,而值是盒子的数组。
let grouped = boxes.reduce([Int:[Box]]()) { (res, box) -> [Int:[Box]] in var res = res res[box.thingsInside] = (res[box.thingsInside] ?? []) + [box] return res }
现在分组为一个,[Int:[Box]]并具有以下内容
[ 2: [Box(name: "Box 1", thingsInside: 2), Box(name: "Box 4", thingsInside: 2)], 3: [Box(name: "Box 2", thingsInside: 3), Box(name: "Box 5", thingsInside: 3)], 1: [Box(name: "Box 0", thingsInside: 1), Box(name: "Box 3", thingsInside: 1), Box(name: "Box 6", thingsInside: 1)] ]