首页 > 解决方案 > 在 Swift 中,是否有将数组拆分为前缀和后缀的内置方法?

问题描述

Swift 上是否有一个内置方法Array将其分成两部分,保留所有元素的顺序?

类似于Array.prefixArray.suffix的东西合二为一?

我知道partitionand split,但它们分别不保留顺序和大小。

例子:

[1,2,3,5,6,2,3,5].cut(where: { $0 < 5 })
>>> ([1,2,3], [5,6,2,3,5])

标签: swift

解决方案


恐怕没有这样的功能,这很遗憾,因为我现在已经多次需要它了。不过,自己动手很容易:

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]))

推荐阅读