gpt4 book ai didi

ios - 在 `filter` 之后或通过查找 `firstIndex that ` 包含快速从数组中删除项目`

转载 作者:行者123 更新时间:2023-11-28 13:33:33 25 4
gpt4 key购买 nike

我有两个 Book 数组

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( { $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 的方法 mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows:

tempArray.removeAll { $0.title.contains("Some Title") }

Playground 测试:

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"

关于ios - 在 `filter` 之后或通过查找 `firstIndex that ` 包含快速从数组中删除项目`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com