vendredi 30 janvier 2015

Add "blocking" to Swift for-loop

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?


Aucun commentaire:

Enregistrer un commentaire