0

I was trying to generate to read values from a SQLite database using Swift on my iOS project with Xcode 11.

This is my code:

var queryStatementString = "SELECT CpfVeterinario, CpfCnpjProdutor, nomeAnimal, QuantAnimaisEq, QuantAnimaisAs, QuantAnimaisMu"
    queryStatementString += " FROM RES_DADO;"
    var queryStatement: OpaquePointer? = nil
    
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        while sqlite3_step(queryStatement) == SQLITE_ROW {
            let id = sqlite3_column_int(queryStatement, 0)
            let CpfVeterinario = String(describing: String(cString: sqlite3_column_text(queryStatement, 1)))
            let CpfCnpjProdutor = String(describing: String(cString: sqlite3_column_text(queryStatement, 2)))
            var nomeAnimal = String(describing: String(cString: sqlite3_column_text(queryStatement, 3)))

In the last line of the code

var nomeAnimal = String(describing: String(cString: sqlite3_column_text(queryStatement, 3)))

the app crashes because the value recorded in the database is null

I got this error:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file my-path/CDA/DBHelper.swift, line 312

How can I fix this problem?

Per example, when the value in the database is null, is it possible to use an empty string?

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
fabiobh
  • 705
  • 2
  • 13
  • 33
  • 1
    Since the database value is Null, String(...) has nothing to work with. You can check if the values are null before doing the conversion or provide a dummy value like an empty string. – john elemans Mar 03 '21 at 20:20
  • How can I check if the value is null? – fabiobh Mar 03 '21 at 21:33
  • 1
    How about something like this: if let stringFromQuery = sqlite3_column_text(queryStatement, 3) as? String { ... }. this way, you try casting the query response to String. if it works, then you can use stringFromQuery inside the if let brackets. if not, you can show an error message in the following else condition. – Onur Çevik Mar 03 '21 at 21:52
  • @OnurÇevik I try that, but didn't work for me. Xcode doesn't allow the code to compile. The suggestion from another user works. It comes from this link https://stackoverflow.com/questions/37235624/unexpectedly-found-nil-while-unwrapping-an-optional-value-while-reading-from-ds – fabiobh Mar 03 '21 at 22:14

0 Answers0