0

With FMDB resultset's resultDictionary method returns a dictionary for each row where the keys are the column names which have a value or are NSNulls. So I am trying to figure out how best to handle these and where.

So with the new update of swift I need to change my code and in the process I am looking at some refactoring.

So as it stands the following line of code's "as" needs to be made to "as?" or "as!" :

resultsArray.append(resultSet.resultDictionary() as Dictionary<String,AnyObject>)

Robert stated I should handle them like this. But it got me thinking about a better solution and thus I am looking for some advice on how I should refactor:

  1. I could get the optional, find nulls and replace the NSNulls with empty string literals "" and this handle empty strings somewhere else in my app.
  2. I could just leave them as is and force unwrap.

public class func queryGetAllRowsFromTableAsArrayOfHashes() -> Array<Dictionary<String,AnyObject>>? {

var resultsArray = Array<Dictionary<String,AnyObject>>()
let database = DBUtility.getDatabaseHandle()

//Perform query and place result into a dictionary.
self.log().info("Getting all rows from: \(self.getTableName())")
if let resultSet = database.executeQuery(self.getAllRowsStatement()) {
    self.log().info("Query run")
    while resultSet.next() {
        //adds a dictionary of the result row to the array.
        resultsArray.append(resultSet.resultDictionary() as! Dictionary<String,AnyObject>)
    }
    self.log().info("Results array: \(resultsArray)")
    return resultsArray;
}else{
   self.log().error("DB Error: \(database.lastErrorMessage())")
}
return nil;
}

Anyone got some advice on where this should be tackled?

Nizam
  • 4,569
  • 3
  • 43
  • 60
Nate Uni
  • 933
  • 1
  • 12
  • 26

1 Answers1

1

You can simply put a check in if statement like this

if var dict = resultSet.resultDictionary() as Dictionary<String,AnyObject> 
{
  resultsArray.append(resultSet.resultDictionary() as! Dictionary<String,AnyObject>)
}

It will only append the value in array if there is non null value. hope it will help you.If value is null then if statement will not be executed.

Krishna Verma
  • 814
  • 2
  • 8
  • 23