Laura M Laura M - 1 year ago 65
Swift Question

Iterate through array and start a new array whenever a certain value is found

Say i have the following array:

array = ["a", "b", "c", "new", "d", "e", "f", "g", "new", "h", "i", "new"]

I want to create a new array every time I find the value "new".

So I would end up with:

array1 = ["a", "b", "c"]
array2 = ["d", "e", "f", "g"]
array3 = ["h", "i"]

What would be the best way to do this?

Answer Source

As the name implies you can split arrays with the split function, however that returns ArraySlice objects.

To get arrays back from the slices you need to map them (credits to Martin R)

let array = ["a", "b", "c", "new", "d", "e", "f", "g", "new", "h", "i", "new"]
let splittedArrays = array.split(separator: "new").map(Array.init)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download