将随机元素添加到数组(swift)

时间:2017-11-15 13:32:50

标签: ios arrays swift uitableview swift3

我有一个带有tableView的VC,我通过从tableView的行中多次选择项目来手动填充数组。在这个VC我有一个数组

var list : [QCategoryy] = [QCategoryy]()
list = NearbyPlaces.getCategories()

其中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
    }

这些项目(酒吧,健身房,水疗中心等)将填充我的tableView单元格,当我选择它们时,我将创建我的数组selectedCategories,你可以在这里看到:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            let selectedCategories: [QCategoryy] = tableView.indexPathsForSelectedRows?.map({ (indexPath) -> QCategoryy in
                return list[indexPath.row] }) ?? []

            if let selectedRows = tableView.indexPathsForSelectedRows {

                if let vc : nextClass = segue.destination as? nextClass {


                vc.categories = selectedCategories


            }
        }
    }
}

现在我想知道如何在不选择tableView的单元格的情况下填充此数组(selectedCategories),但是通过按下按钮以随机方式,所以我想用我的随机项填充数组var list : [QCategoryy] = [QCategoryy]()点击按钮,我该怎么办?

更新

struct QCategoryy {
    var name: String
    var image: UIImage
    var isSelected = false

    init(name:String, image:UIImage) {
        self.name = name
        self.image = image

    }
}

extension QCategoryy: ExpressibleByStringLiteral {


    init(stringLiteral value: String) {
        self.name = value
        self.image = UIImage()

    }
    init(unicodeScalarLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
    init(extendedGraphemeClusterLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
}

1 个答案:

答案 0 :(得分:1)

您可能想要的路线是“混乱”类别数组,然后从数组中获取第一个 n 个元素。

假设您有一组数字1到10:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

你想得到6个随机元素。如果您只是进行了6次Get Random Element类型的通话,则很可能最终会出现重复。

因此,如果您对阵列执行Shuffle,则新阵列可能如下所示:

[7, 2, 9, 5, 3, 4, 1, 10, 8, 6]

你可以得到前6个元素 - 它们是随机的,没有重复。

元素可以是任何东西......我只是在这里显示数字以供解释。

修改

例如......将此代码添加到您的项目中:

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

然后,在准备segue时,你可以这样做:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            if let vc : nextClass = segue.destination as? nextClass {

                // use ALL QCategoryy objects, in random order
                vc.categories = NearbyPlaces.getCategories().shuffled()

                // or, use 4 random QCategoryy objects
                //vc.categories = NearbyPlaces.getCategories().shuffled()[0...3]

            }
        }
    }
}

可以在此处找到此随机播放及其他内容:https://stackoverflow.com/a/24029847/6257435