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

标签 ios swift random shuffle ios10

我正在尝试随机分配一组餐食(目前为 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

I.e 看起来位置在变化,但餐点名称保持不变。

任何帮助将不胜感激。

最佳答案

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

myMeals = shuffleArray(array: myMeals)

关于ios - 为什么我的对象位置随机但不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38923093/

相关文章:

ios - 如何移动逻辑以显示 UITableViewRowAction 从委托(delegate)方法到 View 模型(MVVM 架构)

android - 发送到设备后过期推送通知

swift - 为什么下面的代码会导致无限递归?

ios - 当不同的按钮通向同一个 ViewController 时,我如何快速知道按下了哪个按钮?

matlab - 在网格上的不同点放置高斯函数

php - 如何将数据库字段设置和更新为随机数

r - 为什么 set.seed() 会影响 R 中的 sample()

ios - 如何最好地将使用一个 UIViewController 将所有页面作为 UIView 处理的图书应用程序转换为 StoryBoarding 和 UIPageView?

ios - 重置 ScrollView 位置的简单方法

ios - UIAnimator 的 UISnapBehavior 可以与 UIScrollview 一起使用吗?