1

Edit: I am not looking for a way to split an array by giving its subarray size, I am looking for a way to split an array by giving the number of subarrays I want. I am saying this because the question has been marked as a duplicate, and the linked question is not what I'm looking for.

My goal would be to take an array like this [String] and turn it into an array like this [[String]], with the subarrays being the parts. Maybe creating a function named partition(into:Int). Sort of like this.

let array = ["1", "2", "3", "4", "5", "6", "7", "8"]
array.shuffle()
array.partition(into:4)

Which would end up like this.

[["3", "1"], ["2", "6"], ["8", "5"], ["4", "7"]]

If there are any extra elements it can add them to any subarray.

Ideally, I would like to remove the extra brackets and the quotation marks to display the list in a TableView, or display each subarray as a TableView section with the rows being the contents of the given subarrays.

3, 1
2, 6
8, 5
4, 7
  • 1
    The answer that was linked as a duplicate tells you how to split your array into sub-arrays of a certain size. In your case, you want to divide it into a certain number of arrays. So take the total size of the starting array, divide it by your desired number of sub-arrays. That gives you the target array size. Feed that into the linked answer. Bada-bing, bada-boom. Done. – Duncan C May 25 '21 at 01:00
  • @DuncanC I tried it and it works but the extra elements are put into an extra subarray at the end. I would have to take the extra elements at the end and spread them throughout the original subarrays. Do you know how I could set up a function that would automatically do this? – Alexis Herrera Vegas May 25 '21 at 15:19

0 Answers0