问题描述
我编写了一个简单的 Bag 类.一个 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
.(我也试过一个变量.)当我需要一个新的温度时,我调用 bag.grab()
,一次在 didMoveToView
中,在适当的时候在 触摸结束
.
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) (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.
我无法让它在 Playground 中孤立地崩溃.这可能很明显,但我很难过.
I can't get it to crash isolated in a Playground. It's probably something obvious but I'm stumped.
推荐答案
Function 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 时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!