0

I am having array and wants to iterate three at time

let array = [1, 2, 3, 4, 5, 7, 8, 9, 10]
// expected output -> [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, optonal, optional)]

i have tried with Sequence

public extension Sequence {
    func pairs() -> AnyIterator<(Element, Element?)> {
        return AnyIterator(sequence(state: makeIterator(), next: { iterator in
            iterator.next().map { ($0, iterator.next()) }
        }))
    }
}

let array = [1, 2, 3, 4, 5, 7, 8, 9, 10].pairs()

// output -> [(1, 2), (3, 4), (5, 6)...]

but i need three elements at a time

Thanks in Advance

  • 1
    Plenty of solutions if you look around, https://stackoverflow.com/questions/31185492/split-large-array-in-array-of-two-elements and https://stackoverflow.com/questions/26691123/how-to-implement-haskells-splitevery-in-swift/26691258#26691258 are two similar questions with solutions – Joakim Danielson Aug 24 '22 at 15:22
  • Another key word for your research would be "Swift array chunk". Because sometimes, having the keywords gives a lot of answers than a description. – Larme Aug 24 '22 at 15:23
  • Does this answer your question? [Swift: what is the right way to split up a \[String\] resulting in a \[\[String\]\] with a given subarray size?](https://stackoverflow.com/questions/26395766/swift-what-is-the-right-way-to-split-up-a-string-resulting-in-a-string-wi) – Gereon Aug 24 '22 at 15:27
  • i am expecting tuple kind of output instead of array of array eg - [(1,2,3), (4,5,6)] – Jayaseelan Kumarasamy Aug 24 '22 at 15:35
  • @JayaseelanKumarasamy much better to output a collection of subsequences. This way you don't duplicate the elements. Check UnfoldedSequence type [Iterate over collection two at a time in Swift](https://stackoverflow.com/a/34551270/2303865) – Leo Dabus Aug 24 '22 at 15:36
  • Btw there is no way to have the last element with a single element unless you use a sequence or subsequence as the collection element. Another option is do declare the second and third elements of your tuple as optionals. – Leo Dabus Aug 24 '22 at 15:39
  • @LeoDabus yes last element second and third element can be optional that’s fine – Jayaseelan Kumarasamy Aug 24 '22 at 16:15
  • You can’t. All elements (tuples) would have to be like that. – Leo Dabus Aug 24 '22 at 17:03

1 Answers1

1

Modern solution:

Add the package Swift Algorithms

and chunk the array

let array = [1, 2, 3, 4, 5, 7, 8, 9]
let chunked = array.chunks(ofCount: 3).map(Array.init)
print(chunked)

however the result is a nested array, not an array of tuples.

Calling map is necessary if you want a real array rather than slices.

vadian
  • 274,689
  • 30
  • 353
  • 361