Skip to content

Instantly share code, notes, and snippets.

@gabrieltheodoropoulos
Last active February 14, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieltheodoropoulos/58f0566e99d677a4bfa801b382ee80c2 to your computer and use it in GitHub Desktop.
Save gabrieltheodoropoulos/58f0566e99d677a4bfa801b382ee80c2 to your computer and use it in GitHub Desktop.
Break an array of any type in smaller arrays
/**
Break the provided array to smaller arrays based on the specified maximum
number of items on each.
- Parameter array: The original array to break in pieces.
- Parameter maxItems: The maximum number of elements that each subarray should contain.
- Parameter datatype: The datatype of the contained data in the original
array.
- Returns: A two-dimensional array that contains the subarrays as elements.
*/
private func breakArray<T>(_ array: [T], inSubArraysOf maxItems: Int, datatype: T.Type) -> [[T]] {
var resultArray = [[T]]()
var temp = [T]()
for (index, item) in array.enumerated() {
temp.append(item)
if (index + 1).isMultiple(of: maxItems) {
resultArray.append(temp)
temp.removeAll()
}
}
resultArray.append(temp)
temp.removeAll()
return resultArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment