0

I am using Swift in a project, and using SQLite.swift for database handling. I am trying to retrieve the most recent entry from my database like below:

func returnLatestEmailAddressFromEmailsTable() -> String{

    let dbPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
    let db = Database("\(dbPath)/db.sqlite3")
    let emails = db["emails"]
    let email = Expression<String>("email")
    let time = Expression<Int>("time")

    var returnEmail:String = ""

    for res in emails.limit(1).order(time.desc) {
        returnEmail = res[email]
        println("from inside: \(returnEmail)")
    }

    return returnEmail

}

I am trying to test the returned string from the above function like this:

println("from outside: \(returnLatestEmailAddressFromEmailsTable())")

Note how I print the value from both inside and outside of the function. Inside, it works every single time. I am struggling with the "from outside:" part.

Sometimes the function returns the correct email, but sometimes it returns "" (presumably, the value was not set in the for loop).

How can I add "blocking" functionality so calling returnLatestEmailAddressFromEmailsTable() will always first evaluate the for loop, and only after this return the value?

stephencelis
  • 4,954
  • 2
  • 29
  • 22
Camillo
  • 544
  • 1
  • 6
  • 24
  • 1
    The for loop is always evaluated, but only for the number of rows that exist. In your case, it seems that the query is returning no rows sometimes. Make sure that your table actually has rows (try outputting `emails.count`). Beyond that, SQLite.swift has a helper method to pluck a single row. You should be able to rewrite the for loop and assignment above with a single line: `return emails.order(time.desc).first?[email]`. This returns a `String?`, though, so use `!` to force-unwrap if you consider it a crash-able offense if the row is nil, or use `?? ""` if you want to return an empty string. – stephencelis Jan 30 '15 at 23:02
  • Wow, thanks Stephen, this helped me a lot. I'd like to take the opportunity to thank you for your fantastic work on the SQLite.swift project. I am so excited to play around with it in my project. I'm really impressed! Keep it up and thanks again! – Camillo Feb 01 '15 at 13:47

0 Answers0