0

Is there a builtin method on Swift Arrays which splits it into two pieces, preserving the order of all elements?

Something akin to Array.prefix and Array.suffix, combined into one?

I'm aware of partition and split, but they don't preserve order and size, respectively.

Example:

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

2 Answers2

5

I'm afraid there isn't such a function, which is a shame, because I've needed it several times now. It's pretty easy to roll your own, though:

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]))
Alexander
  • 59,041
  • 12
  • 98
  • 151
1

Nothing built into Swift natively. My best suggestion would be to make an Array extension and do a findIndex passing in the where parameter, then splitting the Array based on that.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179