2

I created an SQLite table with a row id integer PRIMARY KEY. I used this tutorial to integrate SQLite with my app. I'm trying to add that to an array of Ints. Here's my code:

let all = "select id from \(self.tableName)"
let fullArray = self.dbManager.loadDataFromDB(all)

for currentObject in fullArray {  
    println(currentObject[0])
    println(_stdlib_getDemangledTypeName(currentObject[0]))
    self.tableViewData.append(currentObject[0] as! Int) //tableViewData is an array of Ints
}

Results of println statements:

2
Swift.ImplicitlyUnwrappedOptional

When I run the app, I get the following error at the last line of the code.

Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88).

What am I doing wrong, and how can I fix it?

Jessica
  • 9,379
  • 14
  • 65
  • 136

3 Answers3

0

Try:

self.tableViewData.append(currentObject[0].toInt()) 
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
  • 1
    I get an error saying "`'AnyObject' does not have a member named 'toInt()'`" I think that's Objective-C – Jessica Sep 16 '15 at 17:43
0

Are you sure the data in the array are all Ints? I had a similar problem using the Flickr API, since print() statement showed that it was returning Int values.

However it was actually returning String values. Try casting as a String first, then use Int() to convert to integer if required.

David T
  • 2,724
  • 1
  • 17
  • 27
0

Note the following lines in your tutorial code:

// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);

All the results are converted to strings, that means the DB type integer is not kept in results and you have to use something like:

for currentObject in fullArray as! [String] {  
    // Int(currentObject[0])! in Swift 2
    self.tableViewData.append(currentObject[0].toInt()) 
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270