Search code examples
iosxcodegraphswift3cosmicmind

Swift 3 Graph: FILTER and CONTAINS for Entities


here's my problem.

I have a "allPlayers" array Entity.

I have a "players" Relationship between a "team" and a "allPlayers" entities.

I want a list of all players that are not in this team yet.

So:

func availablePlayer(_ team:Entity) -> [Entity] {

    let playersTeam = players.filter { $0.subject == team }.flatMap { [$0.object] }

    let playersAvailable = allPlayers.filter { !playersTeam.contains($0) }

    return playersAvailable
}

in playersTeam will be stored the allPlayers in players relationship given a team. Then, I want to filter the allPlayers array that not contains the playersTeam.

but the !playersTeam.contains($0) give me an error. Entity has not "contains" method. It only has "contains(where:)"

Any idea?


Solution

  • to answer your question, I will setup your model the way I understand it. First let's setup our Team Entities:

    let tA = Entity(type: "Team")
    tA["name"] = "A"
    
    let tB = Entity(type: "Team")
    tB["name" = "B"
    

    and now some Player Entities.

    let p1 = Entity(type: "Player")
    p1["name"] = "Daniel"
    
    let p2 = Entity(type: "Player")
    p2["name"] = "Eve"
    

    Making a relationship:

    p1.is(relationship: "TeamMember").of(object: ta) 
    

    Now we save it all:

    let graph = Graph()
    graph.sync()
    

    Now we search for all players:

    let search = Search<Entity>(graph: graph).for(types: "Player")
    let players = search.sync()
    

    And now we want all players that are not part of a team, which means they are not part of any relationships with TeamMember Relationship types.

    let result = players.filter { (player) -> Bool in
        return player.relationship(types: "TeamMember").count == 0
    }
    

    That should be it. Let me know if I understood correctly. Thank you!