繁体   English   中英

静态函数在枚举中生成随机类型会导致崩溃,并显示错误“解开Optional值时意外发现nil”

[英]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)返回值05 当它是5 ,您加上1并得到6 ,则VillianType(rawValue: 6)返回nil因为没有对应于6 enum值并且强制展开! 导致它崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM