Jake Walker Jake Walker - 1 year ago 66
Swift Question

Why are my objects location randomised but not showing up?

I am trying to randomise a set of meals (currently 5) such an array of meal objects that I've created which have a property mealTitles. I press randomise, using code:

func shuffleArray<T>(array: Array<T>) -> Array<T>
var array = array
for index in ((0 + 1)...array.count - 1).reversed()
// Random int from 0 to index-1
let j = Int(arc4random_uniform(UInt32(index-1)))

// Swap two array elements
// Notice '&' required as swap uses 'inout' parameters
swap(&array[index], &array[j])

return array

I use a shuffle button and look at if it is shuffling Such:

@IBAction func shuffleButton(_ sender: AnyObject) {
shuffleArray(array: myMeals)
print("Objects: \(shuffleArray(array: myMeals))")
print(myMeals[0].mealTitle, myMeals[1].mealTitle, myMeals[2].mealTitle)

This code produces in the console this:

Objects: [<ParseStarterProject_Swift.Meal: 0x6080002747c0>, <ParseStarterProject_Swift.Meal: 0x60800026ea40>, <ParseStarterProject_Swift.Meal: 0x60000027b400>, <ParseStarterProject_Swift.Meal: 0x60000026d980>, <ParseStarterProject_Swift.Meal: 0x608000267d80>]
Sausages and Mash Chicken Korma Fajitas
Objects: [<ParseStarterProject_Swift.Meal: 0x60000027b400>, <ParseStarterProject_Swift.Meal: 0x60800026ea40>, <ParseStarterProject_Swift.Meal: 0x60000026d980>, <ParseStarterProject_Swift.Meal: 0x6080002747c0>, <ParseStarterProject_Swift.Meal: 0x608000267d80>]
Sausages and Mash Chicken Korma Fajitas

I.e it looks like the location is changing but the meal Title stay the same.

Any help would be much appreciated.

dan dan
Answer Source

Your shuffle method returns a new array that is a shuffled version of the old array, but you aren't doing anything with that return value in your code. You need to assign the shuffled array to your property.

myMeals = shuffleArray(array: myMeals)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download