将arc4random()的结果强制转换为Int时崩溃 [英] Crash when casting the result of arc4random() to Int

查看:75
本文介绍了将arc4random()的结果强制转换为Int时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的Bag类.一个袋子中装有固定比例的温度枚举.它使您可以随机抓取一个,并在装满后自动自动装满.看起来像这样:

I've written a simple Bag class. A Bag is filled with a fixed ratio of Temperature enums. It allows you to grab one at random and automatically refills itself when empty. It looks like this:

class Bag {
    var items = Temperature[]()

    init () {
        refill()
    }

    func grab()-> Temperature {
        if items.isEmpty {
            refill()
        }

        var i = Int(arc4random()) % items.count
        return items.removeAtIndex(i)
    }

    func refill() {
        items.append(.Normal)

        items.append(.Hot)
        items.append(.Hot)

        items.append(.Cold)
        items.append(.Cold)
    }
}

温度枚举看起来像这样:

The Temperature enum looks like this:

enum Temperature: Int {
    case Normal, Hot, Cold
}

我的GameScene:SKScene具有常量实例属性bag:Bag. (我也尝试过使用变量.)当我需要一个新的温度时,我在didMoveToView中一次调用bag.grab(),在适当的时候在touchesEnded中调用一次.

My GameScene:SKScene has a constant instance property bag:Bag. (I've tried with a variable as well.) When I need a new temperature I call bag.grab(), once in didMoveToView and when appropriate in touchesEnded.

随机地,此调用在Bag.grab()中的if items.isEmpty行上崩溃.错误是EXC_BAD_INSTRUCTION.检查调试器显示项目为size=1[0] = (AppName.Temperature) <invalid> (0x10).

Randomly this call crashes on the if items.isEmpty line in Bag.grab(). The error is EXC_BAD_INSTRUCTION. Checking the debugger shows items is size=1 and [0] = (AppName.Temperature) <invalid> (0x10).

编辑:我似乎不了解调试器信息.甚至有效的数组也显示size=1[0] =的无关值.所以那里没有帮助.

Edit Looks like I don't understand the debugger info. Even valid arrays show size=1 and unrelated values for [0] =. So no help there.

我无法让它孤立在操场上.这可能很明显,但是我很困惑.

I can't get it to crash isolated in a Playground. It's probably something obvious but I'm stumped.

推荐答案

函数arc4random返回UInt32.如果您得到的值大于Int.max,则Int(...)强制转换将崩溃.

Function arc4random returns an UInt32. If you get a value higher than Int.max, the Int(...) cast will crash.

使用

Int(arc4random_uniform(UInt32(items.count)))

应该是一个更好的解决方案.

should be a better solution.

(责怪Alpha版本中的奇怪崩溃消息...)

(Blame the strange crash messages in the Alpha version...)

这篇关于将arc4random()的结果强制转换为Int时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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