gpt4 book ai didi

Swift 变量 Nil 导致 fatal error : unexpectedly found nil while unwrapping an Optional value

转载 作者:行者123 更新时间:2023-11-30 10:04:40 25 4
gpt4 key购买 nike

首先,我对 Swift 很陌生,所以在你指责我的问题是一个容易解决的问题之前,请记住这一点。

我正在尝试使用按钮将文本字段的内容发送到表格。这段代码定义了变量,您可以看到发送者:

import UIKit

var bookTitle:String!

class secondViewController: UIViewController {

@IBOutlet weak var titleField: UITextField!

@IBAction func addBook(sender: AnyObject) {
bookTitle = (titleField.text)!
}

这是我收到错误消息的代码:

import UIKit

var cellContent = ["Book 1", "Book 2", "Book 3", "Book 4"]

class firstViewController: UIViewController, UITableViewDelegate {

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

cellContent.insert(bookTitle, atIndex: 0)
//THIS IS THE ERROR: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return cellContent.count
}

通过在线搜索,我认为问题是变量“bookTitle”为零,但我不知道如何解决这个问题。

最佳答案

都是因为你

var bookTitle:String!

因为您是在设置之前访问它的。您可以使用 didSet 进行检查。

var bookTitle: String! {
didSet {
print("did set called")
}
}

您应该使用此声明:

var bookTitle: String?

这更安全,因为访问变量时必须解开变量。您应该阅读有关可选和显式类型的 Swift 文档章节。

供引用:

Because the value of an implicitly unwrapped optional is automatically unwrapped when you use it, there’s no need to use the ! operator to unwrap it. That said, if you try to use an implicitly unwrapped optional that has a value of nil, you’ll get a runtime error.

参见:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/doc/uid/TP40014097-CH31-ID445

章:隐式解包可选类型

关于Swift 变量 Nil 导致 fatal error : unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755390/

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