0

I have this code to shuffle a string in swift. For some reason it is giving an error in Xcode 7.1 "swapping a location with itself is not supported. I thought it was working ok. Any ideas where I have gone wrong much appreciated!

let selectedWord = word1 // word1 is a string
var chars = Array(selectedWord.characters)
chars.shuffleString()
let shuffledWord = String(chars)
word1 = shuffledWord

extension Array {
mutating func shuffleString() {
    for index in 0..<(count - 1) {
        let j = Int(arc4random_uniform(UInt32(count - index))) + index
        swap(&self[index], &self[j]) // error on this line saying 'swapping a location with itself is not supported'
richc
  • 1,648
  • 5
  • 20
  • 48
  • Just an added note — that code will crash if you try it with an empty string, since 0 ..< -1 isn't allowed. – Nate Cook Nov 05 '15 at 21:04
  • 1
    thanks Nate. I just saw that excellent long answer from you and others to this question. Sorry for the duplicate! – richc Nov 05 '15 at 21:31

1 Answers1

2

The swap function changed in a recent version of Xcode to prevent swapping a variable with itself. You can add a guard statement just before your swap to make sure index and j aren't the same:

extension Array {
    mutating func shuffleString() {
        for index in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - index))) + index
            guard i != j else { continue }
            swap(&self[index], &self[j])
        }
    }
}
Nate Cook
  • 92,417
  • 32
  • 217
  • 178