Swift 如何在表中仅显示筛选后的数据

Swift 如何在表中仅显示筛选后的数据,swift,Swift,如何显示deck.status==true的数据,并忽略那些设置为false的对象 数据: var decks: [DeckOfCards] 我现在得到的是: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIde

如何显示deck.status==true的数据,并忽略那些设置为false的对象

数据:

var decks: [DeckOfCards]
我现在得到的是:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell

    if (thedeck.decks[indexPath.row].status == true) {
        cell.label.text = "\(thedeck.decks[indexPath.row].card.name)"
    }
}

你可以在甲板上使用过滤功能

let filteredDecks = decks.filter({$0.status})
将数组筛选为

   self.decks = self.decks.filter {
          (d: DeckOfCards) -> Bool in
          return d.status == true
    }

现在,您的数组将具有过滤后的值。您不需要检查
函数中的
状态
cellForRowAtIndexPath
函数。

这样做是错误的。当您到达
cellforrowatinexpath
时,您已经声明一个单元格应该为此索引路径(因此在数据数组中的该索引处)退出队列。执行此筛选的正确位置是在数据源中

例如,除了
数组外,还可以生成一个计算属性(
filteredecks
),该属性通过过滤
数组来获取其值

var decks = [DeckOfCards]
var filteredDecks: [DeckOfCards] {
    return decks.filter { $0.status }
}
然后可以将此属性用作表视图的数据源

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredDecks.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    cell.label.text = "\(filteredDecks[indexPath.row].card.name)"

    return cell
}
现在,由于此解决方案在每个属性访问上计算
filteredecks
数组,因此如果
deck
是一个大数组,或者如果您经常重新加载表视图,则它可能不是最佳方法。如果是这种情况,并且可以这样做,那么您应该更喜欢使用上面的computed属性中所示的相同方法提前过滤
deck
数组