[Solved] Filter not working in model object – swift


Your structs:

struct User {
    var name: String
    var age: Int
    var hasPet: Bool
    var pets: [Pet]
}

struct Pet {
    var id: Int
    var petName: String
    var colour: String
}

User and pets objects:

 let pet1 = Pet(id: 1, petName: "Lucy", colour: "black, white")
 let pet2 = Pet(id: 2, petName: "Nemo", colour: "white")
 let pet3 = Pet(id: 3, petName: "Scooby-Doo", colour: "white")
 let pet4 = Pet(id: 4, petName: "Garfield", colour: "brown, whiteerktjdfg")

 let user1 = User(name: "Joe", age: 20, hasPet: true, pets: [pet1, pet2])
 let user2 = User(name: "Sophia", age: 30, hasPet: true, pets: [pet3, pet4])

 let users = [user1, user2]

You can filter user who have white pets with below code:

    let whitePets = users.compactMap{user -> (User?) in
        var userWithWhitePets = user
        let pets = userWithWhitePets.pets.filter{$0.colour.contains("white")}
        userWithWhitePets.pets = pets
        return userWithWhitePets.pets.count > 0 ? userWithWhitePets : nil

    }

Hope this will help you 🙂

0

solved Filter not working in model object – swift