快速在过滤器之后或通过查找包含的firstIndex从数组中删除项目

时间:2019-07-12 03:33:20

标签: ios arrays swift filter equatable

我有两个Book个数组

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)'。建议解决此错误?或者,可以在过滤时删除该元素吗?

1 个答案:

答案 0 :(得分:2)

您使用了错误的方法。应该是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的方法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"