0

I looked at a similar problem in the Shuffle Array Swift 3 post and tried the code from the Answer, but I still get the same error on the same line.

        let j = Int(arc4random_uniform(UInt32(countArray - i))) + i

The line above throws the error:

Binary operator '-' cannot be applied to operands of type 'C.IndexDistance' and 'Range C.IndexDistance'

Entire function:

//function used to shuffle imageArray
func shuffle<C: MutableCollection>(_ imageArray: C) -> C where C.Index == Int {
    var imageArray = imageArray
    var countArray = imageArray.count

    for i in [1 ..< countArray] {
        countArray = imageArray.count
        let j = Int(arc4random_uniform(UInt32(countArray - i))) + i
        swap(&imageArray[i], &imageArray[j])
    }
    return imageArray
}

Revised Code (below) Still Returns Same Error:

Binary operator '-' cannot be applied to operands of type 'C.IndexDistance' and 'Range C.IndexDistance'

//function used to shuffle imageArray
func shuffle<C: MutableCollection>(_ imageArray: C) -> C where C.Index == Int {
    var imageArray = imageArray
    var countArray = imageArray.count
    for i in imageArray.startIndex ..< imageArray.endIndex-1 {
        countArray = imageArray.count
        let j = Int(arc4random_uniform(UInt32(countArray - i))) + i
        swap(&imageArray[i], &imageArray[j])
    }
    return imageArray
}
Jimmy Maguire
  • 53
  • 1
  • 4
  • 1
    Well... what's the error? – Alexander Nov 02 '16 at 22:14
  • "Binary operator '-' cannot be applied to operands of type 'C.IndexDistance' and 'Range C.IndexDistance' – Jimmy Maguire Nov 02 '16 at 22:21
  • Oh yeah, that's an annoying one. `MutableCollection` doesn't require `Index` to be an `Int`, it keeps it as an abstract type. I can try taking a look at this tomorrow if it isn't answered already. – Alexander Nov 02 '16 at 22:24
  • Duplicate of [Shuffle array swift 3](http://stackoverflow.com/questions/37843647/shuffle-array-swift-3): Replace `1` by `imageArray.startIndex+1` and `countArray` by `imageArray.endIndex`. – Martin R Nov 02 '16 at 22:27
  • Actually it should be `for i in imageArray.startIndex ..< imageArray.endIndex-1`, your version would never move the *first* array element. – Martin R Nov 02 '16 at 22:35
  • Martin R., I revised the code per your comment (and posted it above) but it still returns the same error. Also, I read the Shuffle Array Swift post several times trying to apply the solution, no luck yet. The line that returns the error is: let j = Int(arc4random_uniform(UInt32(countArray - i))) + i – Jimmy Maguire Nov 03 '16 at 01:59
  • @JimmyMaguire: You did not replace *all* instances of `countArray` by `imageArray.endIndex`... It will compile and run if you do, I tested it. – Martin R Nov 03 '16 at 10:58
  • @MartinR yes, that worked, thank you very much – Jimmy Maguire Nov 14 '16 at 18:21

0 Answers0