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

时间:2018-09-23 23:54:28

标签: swift filter

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

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")

}]

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

3 个答案:

答案 0 :(得分:4)

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

我为书做了一个结构

struct Book {
    let title: String
    let tag: [String]
}

创建了一个这样的数组

var books: [Book] = []

哪个是空的。

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

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)

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

print (books.count)

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

let filtered = books.filter{ $0.tag.contains("Psychology") } 
filtered.forEach { print($0) }

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

  

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

     

Book(书名:“ Freakonomics”,标签:[“ Economics”,“ non-fiction”,   “心理学”])

答案 1 :(得分:1)

将图书表示为元组数组,分别具有书名和标签的命名参数title和tag。

let books:[(title:String, tags:String)] = [

    (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")

]

您要搜索标签Psychology

let searchedTag = "Psychology"

我们可以使用filter函数来过滤books数组中仅包含我们要查找的标签的项目。

let searchedBooks = books.filter{ $0.tags.split(separator: ",").map{ return $0.trimmingCharacters(in: .whitespaces) }.contains( searchedTag ) }

print(searchedBooks)

在filter方法内部,我们使用split(separator: Character)方法从书籍标签创建了标签项目数组。接下来,使用map函数,从每个标签中删除前导和尾随空格。最后,使用.contains(element)方法,测试我们要查找的标签是否在此数组中。仅返回通过此测试的元组,其余的将被滤除。

结果是:

  

[(title:“龙纹身的女孩”,标签:“心理学,神秘,惊悚片”),   (标题:“ Freakonomics”,标签:“ Economics,non-fiction,Psychology”)]

答案 2 :(得分:0)

我认为这对于避免输入错误的情况更为有用。

books.filter( { $0.tag.range(of: searchText, options: .caseInsensitive) != nil}