0

I've got a SQL database using SQLite.Swift which I've got working with the functions I need in my main view controller. I've now tried to move the database, along with the functions, over to another class as I'll need to access it from another view controller (a total of two need access.

The database file and table are created fine but as soon as I go to view or modify the database I get: // Unexpectedly found nil while implicitly unwrapping an Optional value

I've added the errors into the code where they occur. I'm new to Swift and am confused as everything works fine if the code is in the main view controller. Any help would be much appreciated!

My code for the class:

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")
    }
}
}

My code for the view controller:

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()}

 }

1 Answers1

0

This error is telling you that while you are expecting those fields to have values they actually don't. For example, in your try for the database in ViewDate, you are looking for viewToday but since that value is nil you app crashes. I would check to make sure your calls to the db are correct and if so make sure you have data there.

Also check the Apple documentation for unwrapping optionals so you don't get hard crashes but a simple error message.

Scott
  • 91
  • 6
  • Thank you for your answer. Currently working my way through the linked info. What I'm confused by is that it works when not split into functions and the save line function to add to the database also results in the optional error. – Lizzy Brown Jul 02 '20 at 10:47