Swift 语法过滤器无法使用
Swift syntax filter cannot be used
我有一个空数组:
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({ [=14=] != 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)
我做错了什么?
您正在使用一个部分的过滤数组更新 indexPathArray
。编译器很困惑,因为您正在用 filter
更新 [[NSIndexPath]]
变量,这将导致 [NSIndexPath]
.
而不是:
indexPathArray = indexPathArray[indexPath.section].filter { [=10=] != indexPath }
您应该改为更新该特定部分,例如:
indexPathArray[indexPath.section] = indexPathArray[indexPath.section].filter { [=11=] != indexPath }
Rob 的 post 确实回答了您的问题。
另请考虑,如果您只需要跟踪所选索引,那么使用 Set
比您正在使用的 array of array of IndexPath
更容易。
var set = Set<NSIndexPath>()
添加索引路径
set.insert(indexPath)
检查 IndexPath 是否在集合中
set.contains(indexPath)
删除索引路径
set.remove(indexPath)
我有一个空数组:
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({ [=14=] != 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)
我做错了什么?
您正在使用一个部分的过滤数组更新 indexPathArray
。编译器很困惑,因为您正在用 filter
更新 [[NSIndexPath]]
变量,这将导致 [NSIndexPath]
.
而不是:
indexPathArray = indexPathArray[indexPath.section].filter { [=10=] != indexPath }
您应该改为更新该特定部分,例如:
indexPathArray[indexPath.section] = indexPathArray[indexPath.section].filter { [=11=] != indexPath }
Rob 的 post 确实回答了您的问题。
另请考虑,如果您只需要跟踪所选索引,那么使用 Set
比您正在使用的 array of array of IndexPath
更容易。
var set = Set<NSIndexPath>()
添加索引路径
set.insert(indexPath)
检查 IndexPath 是否在集合中
set.contains(indexPath)
删除索引路径
set.remove(indexPath)