通过属性过滤对象数组,使用Swift中的值数组

kqqjbcuj  于 2023-08-02  发布在  Swift
关注(0)|答案(3)|浏览(118)

使用值数组,根据对象的某个属性筛选对象数组的最有效方法是什么?我可以遍历这些项目,但我忍不住想,使用Array.filter和Array.contains是一种非常有效的方法--我只是对Swift不够精通,无法将这些片段放在一起。
例如,如果我有一个包含Book对象的数组,每个对象都有一个String author属性,我如何过滤它以只显示John Smith、亚瑟Price或大卫Jones的书?
沿着如下的东西:

Class Book {
    var author : String = String()
}

var books : Array = [Book]()
//books added elsewhere

let authors = ["John Smith", "Arthur Price", "David Jones"]

let filteredBooks = books.filter({authors.contains({($0 as Book).author})})

字符串

toe95027

toe950271#

这就是我在操场上工作的原因,为什么这是不好的?

class Book {
    var author = String()

    init(author:String){
        self.author = author
    }
}

var allBooks: [Book] = []

allBooks.append(Book(author: "John Smith"))
allBooks.append(Book(author: "Arthur Price"))
allBooks.append(Book(author: "David Jones"))
allBooks.append(Book(author: "Somebody Else"))

let authors = ["Arthur Price", "David Jones"]

let filteredBooks = allBooks.filter({authors.contains($0.author)})

filteredBooks       // [{author "Arthur Price"}, {author "David Jones"}]

字符串

ffscu2ro

ffscu2ro2#

你也可以用一些

let authorsAndBooks = authors.map { 
   (authorName) -> (String, [Book]) 
      in (authorName, 
      allBooks.filter({ $0.author == authorName })
   ) 
 }

字符串
这将是元组数组,第一个元素是作者的名字,第二个元素是他的书数组,以防作者写了多本书。

wf82jlnq

wf82jlnq3#

我建议你按作者做一个图书索引:

let book = Book(author: "Arsen")
let bookIndex = [book.author: [book]]

字符串
现在,您可以快速访问按作者筛选的书籍:

bookIndex["Arsen"] // => [Books]


对于多个作者:

var results = [Book]()
for author in authors {
    if let books = bookIndex[author] {
        results += books
    }
}

results

相关问题