【问题标题】:Swift syntax filter cannot be used不能使用 Swift 语法过滤器
【发布时间】:2016-01-26 09:29:04
【问题描述】:

我有一个空数组:

var indexPathArray: [[NSIndexPath]] = [[]]

我有一个在多个部分中包含多行的 tableView。 当在 UITableView 中按下一个单元格时,它会将 NSIndexPath 添加到数组中,如下所示:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        indexPathArray[indexPath.section].append(indexPath)
    }

如果第 1 节第一行的单元格被选中,前面的方法会将 NSIndexPath 添加到 indexPathArray 的第一个数组中。结果将如下所示:

[ [indexPath], [],[] ]

当我取消选择单元格时,我想过滤掉我选择的内容。我实现了以下:

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    indexPathArray = indexPathArray[indexPath.section].filter({ $0 != indexPath   })
}

在 indexPathArray 中的每个数组中,如果取消选择相同的 indexPath 项,我基本上会尝试取出。例如,如果我双击一个单元格两次,indexPath 项将被添加并被过滤功能删除。

但是,它在过滤器函数上抛出一个错误:

Cannot invoke 'filter' with an argument list of type '(@noescape (NSIndexPath) throws -> Bool)'
expected an argument list of type (@noescape (Self.Generator.Element) throws -> Bool)

我在这里做错了什么?

【问题讨论】:

  • 你为什么不用-indexPathsForSelectedRows

标签: ios arrays swift uitableview nsindexpath


【解决方案1】:

Rob 的帖子确实回答了您的问题。

还请注意,如果您只需要跟踪选定的索引,那么使用Set 比您使用的array of array of IndexPath 更容易。

var set = Set<NSIndexPath>()

添加索引路径

set.insert(indexPath)

检查 IndexPath 是否在 Set 中

set.contains(indexPath)

删除 IndexPath

set.remove(indexPath)

【讨论】:

    【解决方案2】:

    您正在使用一个部分的过滤数组更新indexPathArray。编译器很困惑,因为您使用filter 更新[[NSIndexPath]] 变量,这将导致[NSIndexPath]

    代替:

    indexPathArray = indexPathArray[indexPath.section].filter { $0 != indexPath }
    

    您应该更新该特定部分,例如:

    indexPathArray[indexPath.section] = indexPathArray[indexPath.section].filter { $0 != indexPath }
    

    【讨论】:

    • 感谢罗伯的帮助
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多