Learn Courses My Dashboard

Get Rid Of Duplicates In Array

I am adding an object but don’t want to add the same object twice. I am wondering if there is additional code I can add to help me accomplish that.


    var favArr : [CurrentPlayers] = []
    
    func add(_ player: CurrentPlayers) {
        NotificationCenter.default.post(
            name: .passFavNotification,
            object: player
        )

        favArr.append(player)
        
        for player in favArr {
            if !favArr.contains(player) {
                favArr.append(player)
            }
    }
}

Why are you looping through the array?

Instead of:

    var favArr : [CurrentPlayers] = []
    
    func add(_ player: CurrentPlayers) {
        NotificationCenter.default.post(
            name: .passFavNotification,
            object: player
        )

        favArr.append(player)
        
        for player in favArr {
            if !favArr.contains(player) {
                favArr.append(player)
            }
    }
}

Change it to this so that you test for the player existing in the array and append if the player does not exist.

var favArr : [CurrentPlayers] = []

func add(_ player: CurrentPlayers) {
    NotificationCenter.default.post(
        name: .passFavNotification,
        object: player
    )

    if !favArr.contains(player) {
        favArr.append(player)
    }
}

I tried it like that but what happens is it does not add any object at all.

How is your player structured, and what is the difference between player and currentplayer? Do you have a property within player that turns it into a currentplayer? Perhaps there is a conflict somewhere between player and current player?

That’s crazy. If you pass a player parameter to the add() function that is of type CurrentPlayers it should be added to favArr if it is not already in favArr.

If you set a breakpoint at the NotificationCenter blah blah blah.... and then run the code, what happens if you step over that Notification to the if statement and then issue the debug command po player ?

My player is just an instance of an object of type CurrentPlayers.

I can’t step over to the if statement but I can to the beginning of the loop and when I do po player it shows uninitialized.