2015-02-06 37 views
2

我有一些代碼從segue接收值,並用我有的索引號替換數組中的某個元素。致命錯誤:意外地發現nil,同時展開一個可選值(當添加到數組)

變量的初始化:

var noteTitles: [String] = ["Sample Note"] 
var noteBodies: [String] = ["This is what lies within"] 
var selectedNoteIndex: Int! 
var newTitle: String! 
var newBody: String! 

,我有一個賽格瑞,使得最後的3個值,我想他們是值。

viewDidLoad中()下,我有這樣的:

if newTitle == nil && newBody == nil { 

    } 
    else { 
     println("\(newTitle)") 
     println("\(newBody)") 
     println("\(selectedNoteIndex)") 
     let realTitle: String = newTitle 
     let realBody: String = newBody 
     let realIndex: Int = selectedNoteIndex 
     noteTitles[realIndex] = realTitle 
     noteBodies[realIndex] = realBody 
    } 

我的日誌顯示此:

New Note Title 
This is what lies within 
nil 
fatal error: unexpectedly found nil while unwrapping an Optional value 

,我得到

Thread 1: EXC_BAD_INSTRUCTION(code=EXC_i385_INVOP,subcode=0x0) 

上線

let realIndex: Int = selectedNoteIndex 

誰能告訴我我做錯了什麼?

+1

BTW Swift是一種類型推斷的語言。試一試 !!! – 2015-02-06 05:34:16

+0

檢查答案.. – 2015-02-06 05:40:01

回答

0

我得到這些錯誤的原因是因爲在segueing回主視圖,我沒有使用正確的開卷SEGUE,而是使用其他顯示segue,它刪除以前在視圖控制器中的所有數據。通過創建展開順序,我能夠將細節視圖之前的值保存到細節視圖中,並防止出現錯誤。

-1

因爲您沒有爲selectedNoteIndex分配值,所以它顯示nil。首先,你必須檢查它是否不是零值。

if let selectedNoteIndex = realIndex{ 
    let realIndex: Int = selectedNoteIndex 
} 
+0

這不是如何使用可選綁定 - 嘗試'如果讓realIndex = selectedNoteIndex {...} – Antonio 2015-02-06 09:08:51

1

var varName: Type!聲明的隱含展開可選

這意味着它將在使用varName訪問值時自動解包,即不使用varName!

因此,當它的值實際上是nil時,訪問隱式解包的可選selectedNoteIndexlet realIndex: Int = selectedNoteIndex會導致出現錯誤。


蘋果斯威夫特指南指出:

Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

相關問題