3

I have:

extension MutableCollection where Index == Int { // shuffle elements of self in place

    mutating func shuffleInPlace() {

        if count < 2 { return } // empty and single-element collections don't shuffle

        for i in 0 ..< count - 1 {
            let j = Int( arc4random_uniform( UInt32( count - i ) ) ) + i
            guard i != j else { continue }
            swap( &self[ i ], &self[ j ] )
            ...

...

and I'm getting the error:

Binary operator Binary operator '..<' cannot be applied to operands of type 'Int' and 'Self.IndexDistance'

Does anyone know how to rectify this?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Dribbler
  • 4,343
  • 10
  • 33
  • 53
  • Dave answered this and then his answer disappeared! It was to wrap count - 1 in parentheses: ( count - 1 ), which I verified and it works. Thanks, Dave, sorry I couldn't upvote your answer :( – Dribbler Oct 30 '16 at 20:54
  • 1
    I think you may have the answer here: `Int( arc4random_uniform( UInt32( count - 1 ) ) )` Sounds like count - 1 needs to be of type Int. Yea I deleted because I realized I didn't know the type of count =p and whether my answer helped change it's type. I undeleted... – Dave Thomas Oct 30 '16 at 20:55
  • 1
    If your code comes from [this answer](http://stackoverflow.com/a/24029847/2976878), then note that it has been updated with a Swift 3 version. – Hamish Oct 30 '16 at 20:55
  • 1
    That [answer above ( the duplicate )](http://stackoverflow.com/questions/37843647/shuffle-array-swift-3) is far superior as it takes into account array slices, and should be used instead. – Dave Thomas Oct 30 '16 at 21:08
  • 2
    @DaveThomas: I have linked to that one because it is the identical question. Nate Cook added a Swift 3 version to http://stackoverflow.com/a/24029847/1187415 later, and that should work for slices as well, and even for collections which are not indexed by `Int`. – Martin R Oct 30 '16 at 21:14
  • @MartinR Beautiful. – Dave Thomas Oct 30 '16 at 21:38

1 Answers1

2

Try this instead, wrap count -1 in parenthesis :

for i in 0 ..< (count - 1)
Dave Thomas
  • 3,667
  • 2
  • 33
  • 41