【问题标题】:Select a randomly number of items from a list and add them to another list (Swift)从列表中选择随机数量的项目并将它们添加到另一个列表(Swift)
【发布时间】:2018-05-01 02:04:29
【问题描述】:

我的 VC 中有一个列表

var list : [QCategoryy] = [QCategoryy]()

list = NearbyPlaces.getCategories()
list.shuffled()

其中getCategories() 是函数

static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }

我想做的是从这个列表中随机抽取一些项目并将它们添加到另一个列表中,比如var filteredList = [QCategoryy](),我该怎么做?

更新

我想在用户点击按钮时这样做

【问题讨论】:

  • shuffled() 在做什么?

标签: ios arrays swift swift3


【解决方案1】:

试试这个。它将过滤列表,每个项目有 50% 的机会被过滤。

var filteredList = list.filter { _ in
    arc4random() % 2 == 0
}

对于洗牌,请参阅this 答案。

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2014-06-03
    • 2014-06-25
    • 2021-02-02
    • 2013-01-23
    • 2021-08-25
    • 2011-11-14
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多