分組陣列值
如果我們有這樣的結構
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)]
]