I'm trying to figure out the most efficient way using SWIFT 4 to loop through an array of numbers, get the range of any consecutive numbers and add those to a new array. I could do the standard loop checks but I believe I can use a map filter? -- can someone point me in the right direction?
Beginning:
myNumbersArray:[Int] = [1,2,3,4,10,11,15,20,21,22,23]
Wanted result:
newNumbersArray = [
[1,2,3,4],
[10,11],
[15],
[20,21,22,23]
]
I will post my solution if I figure it out...
My suggestion is IndexSet
where consecutive items are stored as ranges.
rangeView
.let myNumbersArray = [1,2,3,4,10,11,15,20,21,22,23]
let indexSet = IndexSet(myNumbersArray)
let rangeView = indexSet.rangeView
let newNumbersArray = rangeView.map { Array($0.indices) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With