let array: [Int] = [1, 2, 2, 2, 3, 4, 4]
var result: [[Int]] = array.isEmpty ? [] : [[array[0]]]
for (previous, current) in zip(array, array.dropFirst()) {
print(previous,current)
if previous == current {
// 如果相同就加入到同一个数组中
result[result.endIndex-1].append(current)
} else { // 如果不相同 就放到下一个数组中
result.append([current])
}
}
result // [[1], [2, 2, 2], [3], [4, 4]]
// 写成通用扩展
extension Array {
func split(where condition : (Element,Element) -> Bool) ->[[Element]]{
var result: [[Element]] = self.isEmpty ? [] : [[self[0]]]
for (previous, current) in zip(self, self.dropFirst()) {
if condition(previous,current) {
// f
result[result.endIndex-1].append(current)
} else {
result.append([current])
}
}
return result
}
}
print(array.split(where:{$0==$1}))
// 简写成
print(array.split(where: ==))
// [[1], [2, 2, 2], [3], [4, 4]]
网友评论