Removing elements
During the game, the other players caught Cindy and Gina cheating. They should be removed from the game! You know that Gina is last in the players list, so you can remove her easily with the removeLast() method:
var removedPlayer = players.removeLast() print("(removedPlayer) was removed")
// > Gina was removed
This method does two things: It removes the last element and then it returns it, in case you need to print it or store it somewhere else — like in an array of cheaters!
To remove Cindy from the game, you need to know the exact index where her name is stored. Looking at the list of players, you see that she’s third in the list, so her index is 2.
removedPlayer = players.remove(at: 2) print("(removedPlayer) was removed")
// > Cindy was removed
But how would you get the index of an element if you didn’t already know it? There’s a method for that! index(of:) returns the first index of the element, because the array might contain multiple copies of the same value. If the method doesn’t find the element, it returns nil.
Mini-exercise
Use index(of:) to determine the position of the element "Dan" in players.