ios - 在“过滤器”之后或通过查找“包含”的“firstIndex”从数组中快速删除项目
问题描述
我有两个Book
s数组
var tempArray = [Book]()
var filteredArray = [Book]()
在哪里
struct Book: Codable, Equatable {
let category: String
let title: String
let author: String
}
tempArray
如果title
匹配,我想从中删除一本书。我可以像这样过滤tempArray
搜索"Some title"
filteredArray = tempArray.filter( { $0.title.range(of: "Some Title", options: .caseInsensitive) != nil } )
我正在尝试删除
if let i = tempArray.firstIndex(of: { $0.title.contains("Some Title") }) {
tempArray.remove(at: i)
}
但得到这个Cannot invoke 'contains' with an argument list of type '(String)'
。修复此错误的建议?或者,可以在过滤时删除元素吗?
解决方案
您使用了错误的方法。它应该func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
代替func firstIndex(of element: Book) -> Int?
if let i = tempArray.firstIndex(where: { $0.title.contains("Some Title") }) {
tempArray.remove(at: i)
}
另一种选择是使用RangeReplaceableCollection
's 方法mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows
:
tempArray.removeAll { $0.title.contains("Some Title") }
游乐场测试:
struct Book: Codable, Equatable {
let category, title, author: String
}
var tempArray: [Book] = [.init(category: "", title: "Some Title", author: "")]
print(tempArray) // "[__lldb_expr_12.Book(category: "", title: "Some Title", author: "")]\n"
tempArray.removeAll { $0.title.contains("Some Title") }
print(tempArray) // "[]\n"
推荐阅读
- html - 沿侧面图像垂直对齐文本
- javascript - d3.js 刷区域映射到域值
- python - 如何仅在过去 365 天使用 group by 对 pandas 数据帧执行滚动求和
- go - 在测试文件中导入类型给出了“未定义”变量
- editor - 跳过长行的 Visual Studio 代码标记化
- scala - 将回调传递给函数以在 Scala 未来的 onComplete 方法上注册
- python - 语法 Keras 层定义
- php - 会话处于活动状态时,Devilbox pgMyAdmin 错误无法更改会话名称
- java - 当用户未使用远程桌面登录时,无法运行 powershell.exe 并使用 Invoke-WmiMethod 执行 ps1 文件
- gradle - 如何防止 gradle 任务覆盖由调用 groovy 类创建文件的自定义任务创建的文件