![](/img/trans.png)
[英]Crash: fatal error: unexpectedly found nil while unwrapping an Optional value
[英]Static func to generate random type in enum causes crash with error “unexpectedly found nil when unwrapping an Optional value”
因此,我从Ray Wenderlich上的教程获得了这段代码的基础: http ://www.raywenderlich.com/75270/make-game-like-candy-crush-with-swift-tutorial-part-1
问题是,有时在调用该函数时,它会使应用程序崩溃,并返回错误“在展开可选值时意外发现nil”,我很确定nil值来自正在设置的rawValue。
我的代码:
enum VillianType: Int {
case Unknown = 0, ammo, money, one, two, three
static func random() -> VillianType {
return VillianType(rawValue: Int(arc4random_uniform(6)) + 1)!
}
var spriteName: String {
let spriteNames = [
"ammo",
"money",
"one",
"two",
"three"
]
return spriteNames[rawValue]
}
}
我了解这里发生的基本概念,但这是我第一次尝试使用枚举,因此请深入解释您的答案。 我的问题是如何解决该错误,为什么会发生。
您的随机数范围太大。
更改:
arc4random_uniform(6)
至:
arc4random_uniform(5)
arc4random_uniform(6)
返回值0
到5
。 当它是5
,您加上1
并得到6
,则VillianType(rawValue: 6)
返回nil
因为没有对应于6
enum
值并且强制展开!
导致它崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.