Filtering Sets based on other Sets

mail@pastecode.io avatar
unknown
swift
2 years ago
1.0 kB
15
Indexable
Never
import Foundation

struct LostFollower: Hashable, Equatable {
    internal var id: String = UUID().uuidString
    func hash(into hasher: inout Hasher) {
        hasher.combine(user.name)
    }
    let user: User
    let dateLost: Date
}

struct User: Equatable, Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(self.name)
    }
    internal var id: String {
        name
    }
    let name: String
}

let users1: Set<LostFollower> = Set([
    LostFollower(user: User(name: "Mike"), dateLost: Date()),
    LostFollower(user: User(name: "Moke"), dateLost: Date()),
    LostFollower(user: User(name: "Make"), dateLost: Date()),
    LostFollower(user: User(name: "Muke"), dateLost: Date())
])


let users2: Set<User> = Set([
    User(name: "Kyle"),
    User(name: "Mike"),
    User(name: "Muke"),
    User(name: "Cool")
])

let filteredUser = users1.filter { follower in 
    !users2.contains(follower.user)
}
///should print Make and Moke since Mike&Muke exists in users2
print(filteredUser)