我正在尝试将一组餐食(目前为5个)随机化,这是我创造的一系列餐具,这些餐具有一些属性餐饮标题。我按下随机,使用代码:
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
}
我使用一个随机按钮,看看它是否在洗牌这样:
@IBAction func shuffleButton(_ sender: AnyObject) {
shuffleArray(array: myMeals)
print("Objects: \(shuffleArray(array: myMeals))")
print(myMeals[0].mealTitle, myMeals[1].mealTitle, myMeals[2].mealTitle)
}
此代码在控制台中生成:
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
是的,看起来位置正在改变,但是用餐标题保持不变。
非常感谢任何帮助。
答案 0 :(得分:2)
您的shuffle方法返回一个新数组,该数组是旧数组的混乱版本,但您不能在代码中使用该返回值执行任何操作。您需要将shuffled数组分配给您的属性。
myMeals = shuffleArray(array: myMeals)