swift 在“filter”之后或通过查找“包含”的“firstIndex”从数组中删除项目
swift remove item from array after `filter` or by finding `firstIndex that `contains`
我有两个 Book
s
数组
var tempArray = [Book]()
var filteredArray = [Book]()
其中
struct Book: Codable, Equatable {
let category: String
let title: String
let author: String
}
如果 title
匹配,我想从 tempArray
中删除一本书。我可以像这样过滤 tempArray
搜索 "Some title"
filteredArray = tempArray.filter( { [=13=].title.range(of: "Some Title", options: .caseInsensitive) != nil } )
我正在尝试删除
if let i = tempArray.firstIndex(of: { [=14=].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: { [=10=].title.contains("Some Title") }) {
tempArray.remove(at: i)
}
另一种选择是使用RangeReplaceableCollection
的方法mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows
:
tempArray.removeAll { [=11=].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 { [=13=].title.contains("Some Title") }
print(tempArray) // "[]\n"
我有两个 Book
s
var tempArray = [Book]()
var filteredArray = [Book]()
其中
struct Book: Codable, Equatable {
let category: String
let title: String
let author: String
}
如果 title
匹配,我想从 tempArray
中删除一本书。我可以像这样过滤 tempArray
搜索 "Some title"
filteredArray = tempArray.filter( { [=13=].title.range(of: "Some Title", options: .caseInsensitive) != nil } )
我正在尝试删除
if let i = tempArray.firstIndex(of: { [=14=].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: { [=10=].title.contains("Some Title") }) {
tempArray.remove(at: i)
}
另一种选择是使用RangeReplaceableCollection
的方法mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows
:
tempArray.removeAll { [=11=].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 { [=13=].title.contains("Some Title") }
print(tempArray) // "[]\n"