gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:41:55 26 4
gpt4 key购买 nike

我有一些代码从 segue 接收值,并用我拥有的索引号替换数组的某个元素。

变量的初始化是:

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

我有一个 segue,它使最后 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

谁能告诉我我做错了什么?

最佳答案

var varName: Type! 声明一个隐式展开的可选

这意味着当使用 varName 访问值时,它将自动解包,即不使用 varName!

因此,当它的值实际上是 nil 时,使用 let realIndex: Int = selectedNoteIndex 访问隐式展开的可选 selectedNoteIndex 会导致错误得到了。


Apple 的 Swift 指南指出:

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.

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value(When adding to a array),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com