[英]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.