arrays - Swift - 尝试使用随机播放功能并出现 fatal error : swapping a location with itself is not supported

标签 arrays swift shuffle

<分区>

我正在尝试使用我在这里找到的这个函数来洗牌数组。谁能告诉我我在这里做错了什么。我收到“ fatal error :不支持与自身交换位置”

var sourceDays = [1,2,3,4,5,6,7]
var yourDays = [1,2,3,4,5,6,7]

func shuffle<C: MutableCollection>( list: C) -> C where C.Index == Int {
    var list = list
    let count = sourceDays.count
    for i in 0..<(count - 1) {
        let j = Int(arc4random_uniform(UInt32(count - i))) + i
        swap(&list[i], &list[j])
    }
    return list
}

@IBAction func go(_ sender: Any) {

    yourDays = shuffle(list: sourceDays)
    print(yourDays)

}

感谢您的帮助。

编辑: 这被标记为与已经提出的问题重复,但那个问题似乎是旧的并且对于 swift 2,并且对我不起作用......不过谢谢。

最佳答案

根据错误描述,您应该将 shuffle 调用更改为:

func shuffle<C: MutableCollection>( list: C) -> C where C.Index == Int {
    var list = list
    let count = sourceDays.count
    for i in 0..<(count - 1) {
        let j = Int(arc4random_uniform(UInt32(count - i))) + i
        if i != j {
            swap(&list[i], &list[j])
        }
    }
    return list
}

您正在尝试将索引与自身打乱顺序,在这种情况下 ij 都具有相同的值。因此错误。

关于arrays - Swift - 尝试使用随机播放功能并出现 fatal error : swapping a location with itself is not supported,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315335/

相关文章:

c++ - 传递给函数的 Default_random_engine 提供可重复的结果

arrays - 如何处理 Firebase 中的空数组?

javascript - 循环遍历数组并将值分配给变量

javascript 将数组合并为单个对象

javascript - 如何将数组对象转换为对象数组?

ios - 无法在 ObjC 中访问 Swift ViewModel 属性

ios - UINavigationBar alpha 自动设置 0.909804

javascript - 如何随机化 JavaScript 数组并确保顺序项不相同

ios - 在 Swift 中设置带边距的 UITableViewCell 框架

c - 使用 const 代替变量声明的空指针