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

时间:2022-09-10 20:03:41

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:

我正在尝试随机化一组饭菜(目前为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
}

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.

任何帮助将非常感激。

1 个解决方案

#1


2  

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.

您的shuffle方法返回一个新数组,该数组是旧数组的混乱版本,但您没有在代码中使用该返回值执行任何操作。您需要将shuffled数组分配给您的属性。

myMeals = shuffleArray(array: myMeals)

#1


2  

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.

您的shuffle方法返回一个新数组,该数组是旧数组的混乱版本,但您没有在代码中使用该返回值执行任何操作。您需要将shuffled数组分配给您的属性。

myMeals = shuffleArray(array: myMeals)