Say I have 5 cells that I created in a table view that have names in them. How would I randomize them after tapping a button and put them in a different order?
Asked
Active
Viewed 983 times
1 Answers
2
Here is some pseudo code:
func randomize()
{
randomize order of the arrayThatFillsTableView
tableView.reloadData()
}
To shuffle your array that fills the tableview, use the following extension:
extension Array
{
mutating func shuffle()
{
for _ in 0..<10
{
sort { (_,_) in arc4random() < arc4random() }
}
}
}
To use it, simply do: arrayThatFillsTableView.shuffle()
The final product is this:
func randomize()
{
arrayThatFillsTableView.shuffle()
tableView.reloadData()
}
Simply call randomize()
whenever you need to shuffle.
Keep in mind that extensions go outside of class declarations.

Will Boland
- 146
- 2
- 13
-
I know I have to reload the tableView's data, I'm just stuck on the actual randomizing. My app allows you to add a name and it will populate a cell. I want to be able to randomize those names. – Gar Jan 20 '17 at 22:55
-
-
@muescha presumably, his question is correct if he stores those names within an array, the end result is the same. – Will Boland Jan 20 '17 at 23:06
-
-
This randomizes the array that fills the table, then just reload the data. – Will Boland Jan 20 '17 at 23:11
-
So i am actually using core data, and I'm pretty sure I have to randomize my fetchedObjects, except I can't add the `shuffle()` function to that array because the array is immutable. – Gar Jan 21 '17 at 00:02