您好,我有一个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")
}]
我想查找与标签Psychology
、(title = "The Girl With the Dragon Tatoo", tag = "Psychology, Mystery, Thriller")
和(title = "Freakonomics", tags = "Economics, non-fiction, Psychology")
相关联的书籍,我该怎么做?
发布于 2018-09-24 10:08:08
所以我很快就这么做了,如果有人能改进这很好,我只是想帮你。
我为书做了一个结构
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)
因此,您现在在book数组中有三个对象。试着检查一下
print (books.count)
现在,您想要过滤心理学书籍。我过滤了心理学标签的数组-过滤器适合你吗?
let filtered = books.filter{ $0.tag.contains("Psychology") }
filtered.forEach { print($0) }
打印出你的两本心理学书中的对象
图书(标题:《龙纹身的女孩》,标签:《心理学》、《神秘》、《寒战》)
书(标题:“魔鬼经济学”,标签:“经济学”,“非小说”,“心理学”)
发布于 2018-09-24 13:58:05
将图书表示为一个元组数组,分别为图书标题和标签命名参数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)
方法,我们测试我们正在寻找的标记是否在这个数组中。只返回通过此测试的元组,其他元组将被过滤掉。
结果是:
(标题:“龙纹身的女孩”,标签:“心理学,神秘,颤栗”),(标题:“魔鬼经济学”,标签:“经济学,非虚构,心理学”)
发布于 2019-09-25 14:02:18
我认为这对于没有输入错误的情况更有用。
books.filter( { $0.tag.range(of: searchText, options: .caseInsensitive) != nil}
https://stackoverflow.com/questions/52471274
复制相似问题