Search code examples
swiftsqlitefmdb

unexpectedly found nil while unwrapping an Optional value: Swift - FMDB - executeQuery


I am new to Swift, FMDB and development in general and I and I am getting a fatal error at runtime : unexpectedly found nil while unwrapping an Optional Value. The error happens on the executeQuery line

Initial try and relevant code:

        var rightAnswer:FMResultSet?
        var memberDatabase:FMDatabase?
    ....
override func viewDidLoad() {
let path = NSBundle.mainBundle().pathForResource("1_celebs", ofType: "sqlite3")
        memberDatabase = FMDatabase(path: path)
        if memberDatabase!.open(){
            print("database is ready")//it works if I comment out the stuff in loadquestion() 
        }
        else{
            print("error finding database")
        }
...
    func loadQuestion(){
        let querySQL = "SELECT Quote, Answer, answerNumber, Celeb1, Celeb2, Celeb3, img1, img2, img3, feedbackImg, Context FROM celebs WHERE answeredRight = 'no' ORDER BY RANDOM() LIMIT 1"

        rightAnswer = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
        rightAnswer!.next()

So then I tried this in func loadQuestion()

let results:FMResultSet? = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: nil)
        while(results?.next() == true)
        {...}

Then I tried this:

do{
   rightAnswer = try memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
   while rightAnswer!.next(){...}
 } catch let error as NSError {
    print("failed: \(error.localizedDescription)")
 }

Then, this:

   do{
   let rs = try memberDatabase!.executeQuery(querySQL, values: nil)
    while rs.next(){...}
} catch let error as NSError {
  print("failed: \(error.localizedDescription)")
}

and I get the same error on the executeQuery line every time! If I try to get away with getting rid of the exclamation and question marks then I get an error on the console saying that the database could not be opened.


Solution

  • The problem is that memberDatabase is nil.

    You should make sure you are populating that variable.

    Another suggestion, you should avoid the force unwrap operator. It does bypass the compiler check for nil (or possible nil) values.

    Swift does offer better solutions like

    Conditional Unwrapping

    if let memberDatabase = memberDatabase {
        try memberDatabase.executeQuery(querySQL, values: nil)
    }
    

    Guard

    guard let memberDatabase = memberDatabase else { return }
    try memberDatabase.executeQuery(querySQL, values: nil)