Search code examples
iosarraysswiftcomputer-sciencecontains

array .contains() in swift expecting a thrown bool?


I am trying to check if the array newGames contains a certain object of class Game. If it does, then I will not add it to the array. If it doesn't, I will add it. My code is as follows:

for game in allGames{
            if(!newGames.contains(game){
                newGames.append(game)
            }
        }

Where allGames is an array of object Game

var allGames = [Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"]), Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"])]

However, I'm getting the error Cannot convert value of type 'Game' to expected argument type '(Game) throws -> Bool'

Why is this occurring? I've tried both

for game in allGames{
            if(!newGames.contains(where: game){
                newGames.append(game)
            }
        }

and

for game in allGames{
            if(!newGames.contains(game throws -> Bool){
                newGames.append(game)
            }
        }

but neither seems to resolve the error and instead only adds to it. What is going on, and why is swift unhappy with the method .contains(game)?


Solution

  • The type of your game instance probably doesn't conform to equatable.

    Either add a conformance to equatable to that type.