Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FMDatabase + swift + request with undefined number of arguments

Tags:

swift

fmdb

I'm trying to send a request to FMDB via a Swift class.

This is working:

self.database.executeQuery("SELECT * FROM foods WHERE id = ?", withArgumentsInArray:[anID])

because I used the method executeQuery(sql, withArgumentsInArray)

But I don't know how to use the classical method with the undefined number of arguments, instead of the one with an array:

self.database.executeUpdate(<#sql: String?#>, withVAList: <#CVaListPointer#>)

I don't know how to write my arguments in withVAList.

like image 254
alex.bour Avatar asked Jun 12 '14 13:06

alex.bour


2 Answers

My solution was to create an FMDatabase wrapper:

let success:Bool = FMDatabaseWrapper().executeUpdate(sql, food.ID?, food.name?)

func executeUpdate(sql:String, _ arguments: AnyObject?...) -> Bool
  {
    return database.executeUpdate(sql, withArgumentsInArray:arguments as NSArray)
  }

It works.

like image 52
alex.bour Avatar answered Oct 20 '22 10:10

alex.bour


The problem is that Swift cannot overload a same-named function with a function that takes a variable number of arguments. Thus, given a "choice" between understanding your call to executeUpdate as a call to executeUpdate:withArgumentsInArray: and a call to executeUpdate:(NSString*)..., the latter never comes up as a possibility.

However, there's really no problem, because you never actually need to call that method. It doesn't do anything except call executeUpdate:withVAList:, which you can call directly yourself, easily, by using the built-in Swift getVaList function (see https://stackoverflow.com/a/24196063/341994).

Or even better, just go right on using executeUpdate:withArgumentsInArray:. If there are no arguments, simply pass nil for the second parameter.

like image 43
matt Avatar answered Oct 20 '22 09:10

matt