简体   繁体   中英

Static func to generate random type in enum causes crash with error “unexpectedly found nil when unwrapping an Optional value”

So I got the basis for this code from a tutorial on Ray Wenderlich: http://www.raywenderlich.com/75270/make-game-like-candy-crush-with-swift-tutorial-part-1

The problem is that occasionally when the function is called it crashes the app and returns the error "unexpectedly found nil while unwrapping an Optional value" I am pretty sure the nil value comes from the rawValue that is being set.

My Code:

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]
}
}

I understand the basic concepts of what is going on here, but this is the first time that I have tried working with enums so please explain your answer in depth. My question is how can I fix the error, and why is it occurring.

Your range for the random numbers is too big.

Change:

arc4random_uniform(6)

to:

arc4random_uniform(5)

arc4random_uniform(6) returns values 0 through 5 . When it is 5 and you add 1 and get 6 , then VillianType(rawValue: 6) returns nil because there is no enum value corresponding to 6 and the force unwrap ! causes it to crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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