Hi I have an array of type Book objects and I'm trying to return all the Books filtered by the tags
attribute. For example
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")
}]
and I want to find the books associated with the tags Psychology
, (title = "The Girl With the Dragon Tatoo", tag = "Psychology, Mystery, Thriller")
and (title = "Freakonomics", tags = "Economics, non-fiction, Psychology")
, how would I do that?
So I quickly did this to help out, if someone can improve that's fine I'm just trying to help.
I made a struct for the books
struct Book {
let title: String
let tag: [String]
}
Created an array of those
var books: [Book] = []
Which is empty.
I created a new object for each book and appended to books
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)
So you've three objects in the books array now. Try to check with
print (books.count)
Now you want to filter for Psychology books. I filtered the array for tags of Psychology - are filters ok for you?
let filtered = books.filter{ $0.tag.contains("Psychology") }
filtered.forEach { print($0) }
Which prints the objects with your two Psychology books
Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology", "Mystery", "Thriller"])
Book(title: "Freakonomics", tag: ["Economics", "non-fiction", "Psychology"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With