使用步进器限制数组 (swift) 内可以包含的对象数



我的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
    }

但我希望在我的视图中控制器,用户可以选择此数组中必须包含的最大对象数 步进Int(steppeR.value) (例如,如果步进器的值为 1,则在我的list中只能是第 一项 getCategories ( 我也已经有一个扩展来洗牌数组

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)
            self.swapAt(firstUnshuffled, 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
    }
}

因为我不希望有限制总是有相同的项目。我怎么能做这样的事情?

用你的static func getCategories()初始化你的主list对吗?然后,当用户更改步进器Int(steppeR.value)的值时,您可以创建一个仅包含所需对象数的过滤列表:

//stepper is equal to 1
var filteredList = [QCategoryy]()
filteredList.append(list[0])
//stepper is equal to 3
var filteredList = [QCategoryy]()
for i in 0..<3 {
  filteredList.append(list[i])
}

最新更新