0

Here's a snippet of code where I get a syntax error I don't understand:

  let deal:[Card] = self.cards
       for hand in hands {
           var data:[Int] = []
           for card:Card in hand.cards {
               let idx = deal.indexOf(card) 
               data.append(idx!)
           }
       }

The error I get is "Cannot invoke 'indexOf' with an argument of type '(Card)'". I don't understand this at all. deal is an [Card]. What should I invoke deal.indexOf with if not a Card? The signature for CollectionType.indexOf in the docs is

func indexOf(element: Self.Generator.Element) -> Self.Index?

If deal is an [Card] isn't Self.Generator.Element equal to Card? I even put in type annotations to check that my variables have the types I expect. What am I missing? (As it happens Card is a struct, but I get the same error if I change it to a class.)

saulspatz
  • 5,011
  • 5
  • 36
  • 47

1 Answers1

6

The problem is that you have not defined what it means for one Card to be equal to another. Thus, Swift cannot know what the index of a given Card is within the array, because it cannot identify the desired Card when it sees it. You need to declare Card as an Equatable and fulfill the requirements of that protocol.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • See, for example, my answer here: http://stackoverflow.com/a/24400073/341994 It deals with the old predecessor of `indexOf`, namely `find`, but the principle is exactly the same. – matt Jul 24 '15 at 19:03
  • That did it, thanks. I wish the error message was a bit more specific, but then I've never seen a compiler whose error messages I liked. – saulspatz Jul 24 '15 at 19:21
  • Well, it's better to look in the headers than in the docs. If you do, you'll see clearly that `indexOf` is not defined on a CollectionType plain and simple, but on a `CollectionType where Generator.Element : Equatable`. – matt Jul 24 '15 at 20:54
  • Please tell me where to find the headers. – saulspatz Jul 25 '15 at 00:41
  • Hover the mouse over the term `indexOf` in your code. Now hold down the Command key. Keep holding it down. Keep hovering. You should see `indexOf` appear underlined. _Now click it!_ – matt Jul 25 '15 at 00:48
  • I knew about this, but it highlights `func indexOf(element: Self.Generator.Element) -> Self.Index?` and I didn't have sense enough to look above the comments and see `Extension CollectionType where Generator.Element : Equatable {`. Thanks again – saulspatz Jul 25 '15 at 02:20