【问题标题】:Add random elements to an array (swift)向数组中添加随机元素(swift)
【发布时间】:2018-04-28 18:11:29
【问题描述】:

我有一个带有 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) 而是通过按下按钮以随机方式填充该数组,所以我想用我的 @987654327 的随机项填充数组@点击按钮,我该怎么做?

更新

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())
    }
}

【问题讨论】:

  • 重复有没有关系?
  • 如果我没有重复会更好

标签: ios arrays swift uitableview swift3


【解决方案1】:

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

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

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

你想得到 6 个随机元素。如果您只是简单地进行了 6 次 Get Random Element 类型的调用,您很可能会得到重复的结果。

因此,如果您对数组执行随机播放,您的新数组可能如下所示:

[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
    }
}

那么,在为转场做准备时,你可以这样做:

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]

            }
        }
    }
}

这个 shuffle 扩展和其他扩展可以在这里找到:https://stackoverflow.com/a/24029847/6257435

【讨论】:

  • 好的理解,这是您的示例 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 与一个数字数组,而不是写一个数组类别的元素?
  • 是的——如果你查看链接中的随机播放代码,你会发现它会随机播放数组中的任何对象——不管它是数字、按钮还是视图的数组、自定义对象等
  • 好的,所以在我的情况下,我必须使用我的列表复制和粘贴该代码?
  • 啊好的我最后还是要修改prepare,现在一切都清楚了,谢谢
猜你喜欢
  • 1970-01-01
  • 2012-11-13
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多