关于Swift:如何对数组进行分组

How to group Arrays

本问题已经有最佳答案,请猛点这里访问。

如何按第一个相同的元素对数组进行分组
例如我有这样的数组"

1
var Array = ["1","1","1","2","2","1","1"]

我想将数组分组为:

1
2
3
4
5
groupedArray = [
        ["1","1","1"],
        ["2","2"],
        ["1","1"]
    ]

谢谢!


您可以扩展Collection,将其Element约束为Equatable协议,并创建一个计算属性以使用reduce(into:)方法返回分组的元素。 您只需要检查last集合上是否有一个与当前元素相等的last元素,如果为true则将当前元素追加到last集合,否则将一个新的collection与其一起:

1
2
3
4
5
6
7
8
9
extension Collection where Element: Equatable {
    var grouped: [[Element]] {
        return reduce(into: []) {
            $0.last?.last == $1 ?
            $0[$0.index(before: $0.endIndex)].append($1) :
            $0.append([$1])
        }
    }
}
1
2
3
4
let array = ["1","1","1","2","2","1","1"]
let grouped = array.grouped
print(grouped)  //"[["1","1","1"], ["2","2"], ["1","1"]]\
"

不要将变量命名为Array,而是要屏蔽Swift.Array类型,这将导致数量众多的怪异bug。 Swift中的变量名称应以小写字母开头。

使用prefix(while:)从指定的索引开始收集相同的元素。 然后继续推进该索引:

1
2
3
4
5
6
7
8
9
let array = ["1","1","1","2","2","1","1"]

var index = 0
var groupedArray = [[String]]()
while index < array.count {
    let slice = array[index...].prefix(while: { $0 == array[index] })
    groupedArray.append(Array(slice))
    index = slice.endIndex
}