从列表中选择随机数量的项目并将它们添加到另一个列表(Swift)

时间:2017-11-17 10:14:21

标签: ios arrays swift swift3

我的VC中有一个列表

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

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

其中getCategories()是func

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](),我该怎么办?

更新

我想在用户点击按钮

时执行此操作

1 个答案:

答案 0 :(得分:0)

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

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

对于改组,请参阅this回答。