2

I keep getting the following error when trying to extend Collection in Swift:

Cannot subscript a value of type 'Self' with an index of type 'Int'

Here is my code:

extension Collection {
    func random() -> Element {
        let randomIndex = count.arc4random
        return self[randomIndex]
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Josh
  • 63
  • 4

1 Answers1

4

The subscript method of Collection needs a Self.Index, not an Int.

You need:

return self[self.index(self.startIndex, offsetBy: randomIndex)]
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • don't forget the `isEmpty` check. just to be safe – staticVoidMan Apr 10 '18 at 07:09
  • @staticVoidMan That would be a good enhancement to the OP method. But it also means their `random` method needs to return an optional `Element`. – rmaddy Apr 10 '18 at 13:31
  • @staticVoidMan the way I use it in my code, there should never be an empty collection. Since this is the case, would it be best to add an `assert(count > 0, "Collection must not be empty")` statement in my extension? – Josh Apr 10 '18 at 17:54
  • `assert(!isEmpty, "...")`. – rmaddy Apr 10 '18 at 17:55