首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Swift中过滤对象数组?

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

Stack Overflow用户
提问于 2018-09-24 07:54:28
回答 3查看 15.3K关注 0票数 6

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

代码语言:javascript
运行
复制
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")相关联的书籍,我该怎么做?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-09-24 10:08:08

所以我很快就这么做了,如果有人能改进这很好,我只是想帮你。

我为书做了一个结构

代码语言:javascript
运行
复制
struct Book {
    let title: String
    let tag: [String]
}

创建了一个数组

代码语言:javascript
运行
复制
var books: [Book] = []

它是空的。

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

代码语言:javascript
运行
复制
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)

因此,您现在在book数组中有三个对象。试着检查一下

代码语言:javascript
运行
复制
print (books.count)

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

代码语言:javascript
运行
复制
let filtered = books.filter{ $0.tag.contains("Psychology") } 
filtered.forEach { print($0) }

打印出你的两本心理学书中的对象

图书(标题:《龙纹身的女孩》,标签:《心理学》、《神秘》、《寒战》)

书(标题:“魔鬼经济学”,标签:“经济学”,“非小说”,“心理学”)

票数 13
EN

Stack Overflow用户

发布于 2018-09-24 13:58:05

将图书表示为一个元组数组,分别为图书标题和标签命名参数title和tag。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
let searchedTag = "Psychology"

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

代码语言:javascript
运行
复制
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)方法,我们测试我们正在寻找的标记是否在这个数组中。只返回通过此测试的元组,其他元组将被过滤掉。

结果是:

(标题:“龙纹身的女孩”,标签:“心理学,神秘,颤栗”),(标题:“魔鬼经济学”,标签:“经济学,非虚构,心理学”)

票数 1
EN

Stack Overflow用户

发布于 2019-09-25 14:02:18

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

代码语言:javascript
运行
复制
books.filter( { $0.tag.range(of: searchText, options: .caseInsensitive) != nil}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52471274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档