Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter on an array of objects in Swift?

Tags:

swift

filter

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?

like image 921
Samm Avatar asked Sep 23 '18 23:09

Samm


1 Answers

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

like image 60
stevenpcurtis Avatar answered Oct 11 '22 18:10

stevenpcurtis