fatal error: unexpectedly found nil while unwrapping an Optional value(When adding to a array)

喜夏-厌秋 提交于 2020-01-05 02:30:12

问题


I have some code that receives value from a segue and replaces a certain element of an array with the index number that I have.

The initialization of the variables is:

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

and I have a segue that makes the last 3 values the values that I want them to be.

under viewDidLoad(), I have this:

    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
    }

My logs show this:

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

and I get

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

on the line

let realIndex: Int = selectedNoteIndex

Can anyone tell me what I'm doing wrong?


回答1:


var varName: Type! declares an implicitly unwrapped optional.

It means that it will be automatically unwrapped when accessing the value with varName, i.e. without using varName!.

Thus, accessing the implicitly unwrapped optional selectedNoteIndex with let realIndex: Int = selectedNoteIndex when its value is actually nil results in the error you got.


Apple's Swift Guide states that:

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.




回答2:


The reason I was getting these errors is because while segueing back to the main view, I was not using the proper unwind segue, and instead using another show segue, which erased all data that had previously been within the view controller. By creating a unwind segue, I was able to keep the values before the segue to the detail view and prevent the error.




回答3:


Because you did not assign value for selectedNoteIndex so it shows nil. First, you have to check whether its not nil value.

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


来源:https://stackoverflow.com/questions/28359143/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valuewhen-addi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!