1

In a Swift iOS 8 project with SQLite, I'm trying to get the number of rows in a table using the SQL COUNT function. From the examples I found in C, I came with this code:

var nRows: Int32 = 0

func getNquestions() {
    let querySQL = "SELECT COUNT(*) from table"
    let results:FMResultSet? = myDatabase.executeQuery(querySQL,withArgumentsInArray: nil)
    if results?.next() == true {
        nRows = results?.intForColumnIndex(0) //STATEMENT GENERATING ERROR
    }
}

After getting a type mismatch error I changed the definition of nRows to Int32 but I keep getting compilation errors (this time "Value of optional type 'Int32? not unwrapped."

Any clues?

zachjs
  • 1,738
  • 1
  • 11
  • 22
Belerofonte
  • 45
  • 2
  • 4

2 Answers2

1

You declare at the beginning of this function that nRows is Int32, not Int32?. Meanwhile, the result of results?.intForColumnIndex(0) returns Int32? due to optional chaining (and perhaps additionally due to the fact that intForColumnIndex() may return an optional).

You must either change your declaration:

var nRows: Int32?

Or use iflet to assign:

if let results = results where results.next() {
    nRows = results.intForColumnIndex(0)
}

(You could also force-unwrap, but it's safer to avoid doing so.)

stephencelis
  • 4,954
  • 2
  • 29
  • 22
1

Try with the statement like this.

SELECT count() FROM contacts

It worked for me. Notice the count syntax without "*".