ios - 陷入循环。很奇怪,因为代码有时可以工作,有时只是卡住

标签 ios swift

我正在为 IOS 编写一款益智游戏。在我的代码中,我需要用一些代表主要数据结构的随机(和非随机数字)填充数组。

func Random(r :  Range<Int>) -> Int {
    return Int(arc4random_uniform(UInt32(r.endIndex  - r.startIndex))) + r.startIndex
} // function to generate random number

var arrWithColors = [Int]() // array that will hold the numbers

//function to that check if an array contains a number in a range already

func checkForNumberInArrayWithRange(r: Range <Int>, n: Int ) -> Bool {
    for i in r.startIndex..<r.endIndex {
        if arrWithColors[i] == n { return true }
    }
    return false
}

// here is the main function where i keep getting stuck. Out of let's say five times it would only work 3 or even less. 


func randHexWithTag() {
    var rNumber : Int = Random(0...5)
        for i in 0...5 {
            while (true) {
                rNumber = Random(0...5)
                if !checkForNumberInArrayWithRange(0...5, n: rNumber) { 
                    break
                }
            }
            arrWithColors[i] = rNumber
        }

        arrWithColors[10] = arrWithColors[1]

        for i in 6...11 {   
            while(true) {
                rNumber = Random(0...5)
                if ((rNumber == arrWithColors[0] && i == 9) || (rNumber == arrWithColors[2] && i == 11)) {
                    continue
                }

                if !checkForNumberInArrayWithRange(6...11, n: rNumber) {
                    break
                }
            }

            if (i != 10) {
                arrWithColors[i] = rNumber
            }

        }

        arrWithColors[13] = arrWithColors[4]

        for i in 12...17 {

            while(true) {
                rNumber = Random(0...5)

                if (rNumber == arrWithColors[3] && i == 12) || (rNumber == arrWithColors[5] && i == 14) {
                    continue
                }
                if !checkForNumberInArrayWithRange(12...17, n: rNumber) {
                    break
                } 
            }

            if (i != 13) {
                arrWithColors[i] = rNumber
            }

        }
}

最佳答案

在第一次调用此行的 checkForNumberInArrayWithRange 期间,上述代码始终会失败:

if arrWithColors[i] == n { return true }

这是因为 arrWithColors 为空,并且索引 i 超出范围

关于ios - 陷入循环。很奇怪,因为代码有时可以工作,有时只是卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443863/

相关文章:

ios - 尝试在 Swift 中找到何时关闭微调器的正确事件

ios - 关闭返回值到外部 block ?

ios - 本地通知 - 重复间隔(Xcode,swift2)

objective-c - 适用于 iOS 的全功能文件下载管理器

ios - 代码签名授权文件与您的配置文件中指定的文件不匹配。

ios - 设置标签自定义控件 ?

swift - 与 iOS 相比,我如何有条件地依赖桌面系统库?

swift - 修复 NSURLConnection 弃用从 Swift 1.2 到 2.0

iphone - 如何减少 OHAttributedLabel 和 drawTextInRect 的内存使用

javascript - 一两秒钟后视频变黑