【问题标题】:swift remove item from array after `filter` or by finding `firstIndex that `contains`在“过滤器”之后或通过查找“包含”的“firstIndex”从数组中快速删除项目
【发布时间】:2019-11-21 19:14:49
【问题描述】:

我有两个Books 数组

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

【问题讨论】:

  • 我不明白。过滤后的数组已删除了不需要的项目。这就是过滤是的。您知道如何过滤,那么问题出在哪里?
  • 在这种情况下,过滤后的数组只包含我想从原始数据中删除的值
  • @matt 根据您的建议,我该如何反转过滤器的工作原理?我不想存储匹配的值,而是存储所有不匹配条件的值?
  • “我怎样才能反转过滤器的工作方式” 使用神奇的词“不”。是感叹号。例如$0.title.contains("Some Title") 的反义词是!$0.title.contains("Some Title")。

标签: ios arrays swift filter equatable


【解决方案1】:

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

【讨论】:

  • 我确实尝试过。它给我留下了Incorrect argument label in call (have 'where:', expected 'of:'),Replace 'where' with 'of'
  • 您使用的是哪个 Xcode 版本?它在这里编译得很好。
  • 版本 10.2.1 (10E1001)。
  • 对我来说仍然显示与以前相同的错误Cannot invoke 'contains' with an argument list of type '(String)':/
  • 我已经采纳了您的更改并且它正在工作!而是直接使用这一行 var tempArray: [Book] = [.init(category: "", title: "Some Title", author: "")] 我正在从另一个 VC 初始化 tempArray,例如 tempArray = BooksController.favouriteBooks
猜你喜欢
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 2013-04-22
  • 2020-02-16
相关资源
最近更新 更多