gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:29:41 25 4
gpt4 key购买 nike

您好,我有一个 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"),我该怎么做?

最佳答案

所以我很快就做了这个来帮忙,如果有人可以改进那很好,我只是想帮忙。

我为书做了一个结构

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(title: "The Girl With the Dragon Tatoo", tag: ["Psychology", "Mystery", "Thriller"])

Book(title: "Freakonomics", tag: ["Economics", "non-fiction", "Psychology"])

关于swift - 如何在 Swift 中过滤对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52471274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com