致命错误:Swift 2.0不支持与自身交换位置 [英] fatal error: swapping a location with itself is not supported with Swift 2.0

查看:110
本文介绍了致命错误:Swift 2.0不支持与自身交换位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此扩展名,它将创建一个新数组,该数组从给定数组中随机地具有数组组:

I have this extension which will create a new array which have group of arrays randomly from given array:

extension Array {
    var shuffle:[Element] {
        var elements = self
        for index in 0..<elements.count {
            swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ])
        }
        return elements
    }
    func groupOf(n:Int)-> [[Element]] {
        var result:[[Element]]=[]
        for i in 0...(count/n)-1 {
            var tempArray:[Element] = []
            for index in 0...n-1 {
                tempArray.append(self[index+(i*n)])
            }
            result.append(tempArray)
        }

        return result
    }
}

我正在这样使用它:

let mainArr = Array(1...60)
let suffeldArr = mainArr.shuffle.groupOf(10)
print(suffeldArr)

它将显示为:

[[10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60]]

但这在运行时在此行给我一个错误:

But it is giving me an error at run time at this line:

swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ])

哪个说:

致命错误:不支持与自身交换位置

fatal error: swapping a location with itself is not supported

在1.2中可以正常工作,但现在在2.0中则无法工作.

It was working fine in 1.2 but now it is not working in 2.0.

我不知道该怎么解决.

推荐答案

您正尝试与其本身交换元素,则需要执行检查以查看是否不尝试将元素交换至同一位置.数组,就像这样:

You are trying to swap an element with itself, you will need to perform a check to see if you are not trying to swap an element to the same spot in the array, like so:

extension Array {
    var shuffle:[Element] {
        var elements = self
        for index in 0..<elements.count {
            let newIndex = Int(arc4random_uniform(UInt32(elements.count-index)))+index
            if index != newIndex { // Check if you are not trying to swap an element with itself
                swap(&elements[index], &elements[newIndex])
            }
        }
        return elements
    }
    func groupOf(n:Int)-> [[Element]] {
        var result:[[Element]]=[]
        for i in 0...(count/n)-1 {
            var tempArray:[Element] = []
            for index in 0...n-1 {
                tempArray.append(self[index+(i*n)])
            }
            result.append(tempArray)
        }

        return result
    }
}

这篇关于致命错误:Swift 2.0不支持与自身交换位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆