首页 > 解决方案 > 使用 SQLite.Swift 访问数据库时在展开可选时发现 nil

问题描述

我有一个使用 SQLite.Swift 的 SQL 数据库,我可以在我的主视图控制器中使用我需要的功能。我现在尝试将数据库连同函数一起移动到另一个类,因为我需要从另一个视图控制器访问它(总共有两个需要访问。

数据库文件和表创建得很好,但是当我查看或修改数据库时,我得到://意外发现 nil,同时隐式展开可选值

我已将错误添加到发生错误的代码中。我是 Swift 新手,如果代码在主视图控制器中,一切正常,我感到很困惑。任何帮助将非常感激!

我的课程代码:

class testClass: UIViewController {


// db
var database: Connection!
//table
let starLinesTable = Table("starLinesTable")
// columns - "" = name
let id = Expression<Int>("id")
let date = Expression<String>("date")
let line = Expression<String>("line")


func createDBTable() {
    
    // create db
    do {
        let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let fileURL = documentDirectory.appendingPathComponent("starlineDB").appendingPathExtension("sqlite3")
        let databse = try Connection(fileURL.path)
        self.database = databse
    } catch {
        print("error creating documentDirectory")
    }
    
    // creates table ..................................................................................
    let createTable = self.starLinesTable.create { (table) in
        table.column(self.id, primaryKey: true)
        table.column(self.date, unique: true)
        table.column(self.line)
    }
    do {
        try self.database.run(createTable)
        print("created table")
    } catch {
        print("error creating table")
    }
    
}



func functionTest() {
    print("connection has been made")
}



func viewDate() {
    do {
        let viewToday = starLinesTable.filter(date == "today")
        for i in try database.prepare(viewToday) { // Unexpectedly found nil while implicitly unwrapping an Optional value
            print("id: \(i[id]). date: \(i[date]). line: \(i[line])")
        }
    } catch {
        print(error)
        print("error viewing today")
    }
}



func viewAll() {
    do {
        let data = try self.database.prepare(self.starLinesTable) // Unexpectedly found nil while implicitly unwrapping an Optional value
        for i in data {
            print("id: \(i[self.id]). date: \(i[self.date]). line: \(i[self.line])")
        }
    } catch {
        print(error)
        print("couldn't view db")
    }
}

func saveLine() {
    
    let userDate = "dateInput.text"
    let userLine = "this is a line"
    let addLine = self.starLinesTable.insert(self.date <- userDate, self.line <- userLine)
    
    do {
        try self.database.run(addLine) // Unexpectedly found nil while implicitly unwrapping an Optional value
        print("added new line")
    } catch {
        print(error)
        print("didn't add new line")
    }
}
}

我的视图控制器代码:

import UIKit
import SQLite

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

    testClass().createDBTable()
  
}

@IBOutlet weak var dateInput: UITextField!
@IBOutlet weak var lineInput: UITextField!


@IBAction func saveButton(_ sender: Any) {
    testClass().saveLine()}


@IBAction func viewAll(_ sender: Any) {
    testClass().viewAll()}


@IBAction func viewTodayButton(_ sender: Any) {
    testClass().viewDate()}


@IBAction func buttonFunctionTest(_ sender: Any) {
    
    testClass().functionTest()}

 }

标签: swiftsqlite

解决方案


此错误告诉您,虽然您期望这些字段具有它们实际上没有的值。例如,在您尝试使用 ViewDate 中的数据库时,您正在寻找 viewToday 但由于该值为 nil,因此您的应用程序崩溃了。我会检查以确保您对数据库的调用是正确的,如果是,请确保您在那里有数据。

还要检查 Apple 文档以了解解包选项,这样您就不会遇到硬崩溃而是简单的错误消息。


推荐阅读