I'm trying to grab a batch of 3 from an array within a loop. I feel there must be a more elegant way with Swift.
Here's what I have so far:
for (index, item) in allItems.enumerate() {
var batch: [MyType] = []
if index < allItems.endIndex {
batch.append(allItems[index])
}
if index + 1 < allItems.endIndex {
batch.append(allItems[index + 1])
}
if index + 2 < allItems.endIndex {
batch.append(allItems[index + 2])
}
sendBatchSomewhere(batch)
}
Any better and safer way to achieve grabbing a batch? The middle is easy, but of course handling the beginning and end gets a little tricky. Any Swifty ideas?
Update:
Thanks, this works beautifully! Here's the playground version:
import Foundation
typealias MyType = (a: String, b: Int, c: Int)
let allItems1: [MyType] = []
let allItems2 = [
(a: "Item 1", b: 2, c: 3)
]
let allItems3 = [
(a: "Item 1", b: 2, c: 3),
(a: "Item 2", b: 4, c: 5),
(a: "Item 3", b: 6, c: 7),
(a: "Item 4", b: 8, c: 9),
(a: "Item 5", b: 10, c: 11),
(a: "Item 6", b: 12, c: 13),
(a: "Item 7", b: 14, c: 15),
(a: "Item 8", b: 16, c: 17),
(a: "Item 9", b: 18, c: 19),
(a: "Item 10", b: 20, c: 21),
(a: "Item 11", b: 22, c: 23)
]
let testItems = allItems3 // Change to allItems1, allItems2, allItems3, etc
let batchSize = 3
let output = testItems.indices.map { fromIndex -> [MyType] in
let toIndex = fromIndex.advancedBy(batchSize, limit: testItems.endIndex)
return Array(testItems[fromIndex ..< toIndex])
}
print(output) =>
[
[("Item 1", 2, 3), ("Item 2", 4, 5), ("Item 3", 6, 7)],
[("Item 2", 4, 5), ("Item 3", 6, 7), ("Item 4", 8, 9)],
[("Item 3", 6, 7), ("Item 4", 8, 9), ("Item 5", 10, 11)],
[("Item 4", 8, 9), ("Item 5", 10, 11), ("Item 6", 12, 13)],
[("Item 5", 10, 11), ("Item 6", 12, 13), ("Item 7", 14, 15)],
[("Item 6", 12, 13), ("Item 7", 14, 15), ("Item 8", 16, 17)],
[("Item 7", 14, 15), ("Item 8", 16, 17), ("Item 9", 18, 19)],
[("Item 8", 16, 17), ("Item 9", 18, 19), ("Item 10", 20, 21)],
[("Item 9", 18, 19), ("Item 10", 20, 21), ("Item 11", 22, 23)],
[("Item 10", 20, 21), ("Item 11", 22, 23)],
[("Item 11", 22, 23)]
]