简体   繁体   English

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

[英]swift remove item from array after `filter` or by finding `firstIndex that `contains`

I have two arrays of Book s 我有两个Book数组

var tempArray = [Book]()
var filteredArray = [Book]()

where 哪里

struct Book: Codable, Equatable {
    let category: String
    let title: String
    let author: String
}

I want to remove a book from tempArray if a title matches. 如果title匹配,我想从tempArray删除一本书。 I can filter tempArray searching for "Some title" like this 我可以过滤tempArray搜索"Some title"

filteredArray = tempArray.filter( { $0.title.range(of: "Some Title", options: .caseInsensitive) != nil } )

I'm trying this to remove 我正在尝试删除

if let i = tempArray.firstIndex(of: { $0.title.contains("Some Title") }) {
        tempArray.remove(at: i)
    }

but get this Cannot invoke 'contains' with an argument list of type '(String)' . 但是得到这个Cannot invoke 'contains' with an argument list of type '(String)' Advice to fix this error? 建议解决此错误? Or alternatively, can the element be removed while filtering? 或者,可以在过滤时删除元素吗?

You are using the wrong method. 您使用了错误的方法。 It should be func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? 它应该是func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? instead of func firstIndex(of element: Book) -> Int? 而不是func firstIndex(of element: Book) -> Int?

if let i = tempArray.firstIndex(where: { $0.title.contains("Some Title") }) {
    tempArray.remove(at: i)
}

Another option is to use RangeReplaceableCollection 's method mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows : 另一个选择是使用RangeReplaceableCollection的方法来mutating func removeAll(where shouldBeRemoved: (Book) throws -> Bool) rethrows RangeReplaceableCollection的方法:

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

Playground testing: 游乐场测试:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM