Last active
February 14, 2020 12:10
-
-
Save gabrieltheodoropoulos/58f0566e99d677a4bfa801b382ee80c2 to your computer and use it in GitHub Desktop.
Break an array of any type in smaller arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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