Swift: Convert an Optional Binding value to an Integer – SQLite!

Best solution for using SQLite in your Swift project is SQLite Swift. It works perfect and comes with very good documentation.

A problem I was facing was converting a field value to an integer.

In short, this was the problematic code:


let db = try Connection(databasePath)
let stmt = try db.prepare("SELECT someId, someCount, someName FROM someTable")
        
for row in stmt {
    print("row[1] = \(String(describing: row[1]))")
    // ... I need row[1] as Integer!
}

I needed to convert row[1] to an Integer.
I tried many solution, found on multiple forums, none of them really worked.
Finally I came up with this:


let db = try Connection(databasePath)
let stmt = try db.prepare("SELECT someId, someCount, someName FROM someTable")
        
for row in stmt {
    let optionalCount : Int64 = Optional(row[1]) as! Int64
    let lCount = Int(optionalCount)
    // Now I have an integer!

 }

Happy Coding!

Leave a Reply