如何在Swift中过滤对象数组?

Sam*_*amm 2 filter swift

嗨,我有一个类型为Book对象的数组,并且我试图返回按tags属性过滤的所有Books 。例如

var books = [

(title = "The Da Vinci Code", tags = "Religion, Mystery, Europe"), 
(title = "The Girl With the Dragon Tatoo", tags = "Psychology, Mystery, Thriller"), 
(title = "Freakonomics", tags = "Economics, non-fiction, Psychology")

}]
Run Code Online (Sandbox Code Playgroud)

并且我想找到与标记相关的书Psychology(title = "The Girl With the Dragon Tatoo", tag = "Psychology, Mystery, Thriller")并且(title = "Freakonomics", tags = "Economics, non-fiction, Psychology"),我该怎么做?

ste*_*tis 5

因此,我很快就这样做了以帮助他人,如果有人可以改进的话,我只是在尝试提供帮助。

我为书做了一个结构

struct Book {
    let title: String
    let tag: [String]
}
Run Code Online (Sandbox Code Playgroud)

创建了一个数组

var books: [Book] = []
Run Code Online (Sandbox Code Playgroud)

哪个是空的。

我为每本书创建了一个新对象,并将其附加到书中

let dv = Book(title: "The Da Vinci Code", tag: ["Religion","Mystery", "Europe"])
books.append(dv)
let gdt = Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology","Mystery", "Thriller"])
books.append(gdt)
let fn = Book(title: "Freakonomics", tag: ["Economics","non-fiction", "Psychology"])
books.append(fn)
Run Code Online (Sandbox Code Playgroud)

因此,现在在books数组中有三个对象。尝试检查

print (books.count)
Run Code Online (Sandbox Code Playgroud)

现在,您要筛选心理学书籍。我为心理学标签过滤了数组-过滤器适合您吗?

let filtered = books.filter{ $0.tag.contains("Psychology") } 
filtered.forEach { print($0) }
Run Code Online (Sandbox Code Playgroud)

用您的两本心理学书打印对象

图书(书名:“有龙纹身的女孩”,标签:[“心理学”,“神秘”,“惊悚片”))

图书(书名:“ Freakonomics”,标签:[“ Economics”,“ non-fiction”,“ Psychology”])