为什么我的对象位置随机但不显示?

Why are my objects location randomised but not showing up?

我正在尝试随机分配一组餐食(目前为 5 餐),例如我创建的具有 属性 mealTitles 的餐食对象数组。我按随机化,使用代码:

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

也就是说,位置似乎在变,但餐点名称保持不变。

如有任何帮助,我们将不胜感激。

您的随机播放方法 return 是一个新数组,它是旧数组的随机播放版本,但您没有对代码中的 return 值执行任何操作。您需要将打乱后的数组分配给您的 属性.

myMeals = shuffleArray(array: myMeals)