How to filter array of items by another array of items in swift

Viewed 809

I have a model named Item and Tag. Item has multi tags. I need to filter array of items by another array of tags. Tags to be used for filter are given by array of string.

I googled but couldn't find answer to solve my situation.

struct Tag {
    let id: Int
    let name: String
}

struct Item {
    let id: Int
    let tags: [Tag]
}

func filter(items: [Item], contains tags: [String]) -> [Item] {
    // Need to implement filter
}

1 Answers

Chose 1 in 2 option of return:

     func filter(items: [Item], contains tags: [String]) -> [Item] {
        items.filter { (item) -> Bool in
            let tagNames = item.tags.map({ $0.name })
            return tags.allSatisfy(tagNames.contains)
            return Set(tags).isSubset(of: Set(tagNames))
        }
    }
Related