Representing the books as an array of tuples with named parameters title and tags for book title and tags respectively.
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")
]
You want to search for tag Psychology
let searchedTag = "Psychology"
We can use filter function to filter out the items in the books array that only contains the tag we are looking for.
let searchedBooks = books.filter{ $0.tags.split(separator: ",").map{ return $0.trimmingCharacters(in: .whitespaces) }.contains( searchedTag ) }
print(searchedBooks)
Inside the filter method, we have created an array of tag items from book tags using split(separator: Character) method. Next, using map function, we remove the leading and trailing whitespaces from each tag. Finally, using .contains(element) method, we test if the tag we are looking for is in this array. Only the tuples passing this test are returned and the others will be filtered out.
The result is:
[(title: "The Girl With the Dragon Tatoo", tags: "Psychology, Mystery, Thriller"),
(title: "Freakonomics", tags: "Economics, non-fiction, Psychology")]