1

I am reading two different SQLite files and reading the 4th column. In one of the files, the type is REAL and in the other, it's INTEGER.

When I try to extract the value, I am unable to ever determine the type:

for row in try! db.prepare("SELECT * FROM things") {
  let value = row[4]

  print(value) //This logs "Optional(7)" or "Optional(1.2)" etc.

  switch value{

    case let double as Double:
      print("Double: \(double)") //This never gets called...

    case let int as Int:
      print("Int: \(int)") //This never gets called

    default:
      return 0 //This always gets called
  }
}

How can I accurately detect the type of the column?

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128

2 Answers2

1
        switch sqlite3_column_type(sqliteStatement, index) {
        case SQLITE_TEXT:
            // handle text
        case SQLITE_BLOB:
            // handle image
        case SQLITE_NULL:
            // handle null
        case SQLITE_FLOAT:
            // handle float
        case SQLITE_INTEGER:
            // handle integer
        default:
            break
        }
Ted
  • 22,696
  • 11
  • 95
  • 109
0

I figured this out. I needed to check against Int64 instead of Int.

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128
  • For what's it's worth, GRDB.swift lets you just write `let value: Double = row[4]` (which works for both integer and real database values). And when you really need to know the low-level type, you use `switch row[4] as DatabaseValue { case .int64(let int64): ... case .double(let double): ... }`. – Gwendal Roué Dec 15 '17 at 12:02