Swift Arrays上是否有一个内置方法将它分成两部分,保留所有元素的顺序?
类似于Array.prefix和 的东西Array.suffix,合二为一?
我知道partitionand split,但它们分别不保留顺序和大小。
例子:
[1,2,3,5,6,2,3,5].cut(where: { $0 < 5 })
>>> ([1,2,3], [5,6,2,3,5])
Run Code Online (Sandbox Code Playgroud)
恐怕没有这样的功能,太可惜了,因为我现在已经需要它好几次了。不过,自己动手也很容易:
extension RangeReplaceableCollection {
func cut(where belongsInFirstHalf: (Element) -> Bool) -> (SubSequence, SubSequence) {
guard let splittingIndex = self.firstIndex(where: { !belongsInFirstHalf($0) }) else {
return (self[...], SubSequence())
}
return (
self[..<splittingIndex],
self[splittingIndex...]
)
}
}
print([1,2,3,5,6,2,3,5].cut(where: { $0 < 5 })) // => (ArraySlice([1, 2, 3]), ArraySlice([5, 6, 2, 3, 5]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |