String 在Swift中洗牌字符串-不支持交换位置

String 在Swift中洗牌字符串-不支持交换位置,string,swift,shuffle,String,Swift,Shuffle,我有这个代码可以在swift中洗牌字符串。由于某些原因,它在Xcode 7.1中给出了一个错误“不支持将一个位置与自身交换。我认为它工作正常。任何我出错的想法都非常感谢 let selectedWord = word1 // word1 is a string var chars = Array(selectedWord.characters) chars.shuffleString() let shuffledWord = String(chars) word1 = shuffledWord

我有这个代码可以在swift中洗牌字符串。由于某些原因,它在Xcode 7.1中给出了一个错误“不支持将一个位置与自身交换。我认为它工作正常。任何我出错的想法都非常感谢

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'
让selectedWord=word1//word1是一个字符串
var chars=数组(selectedWord.characters)
chars.shuffleString()
设shuffledWord=String(字符)
word1=shuffledWord
扩展阵列{
变异函数shufflesting(){

对于0中的索引,在最新版本的Xcode中,
swap
函数已更改,以防止变量与其自身进行交换。您可以在交换之前添加一条
guard
语句,以确保
index
j
不相同:

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])
        }
    }
}
扩展数组{
变异函数shufflesting(){

对于0中的索引,只需添加一条注释-如果您使用空字符串尝试,代码将崩溃,因为0..<-1是不允许的。谢谢Nate。我刚刚看到您和其他人对此问题的精彩长答案。很抱歉重复!