Add “blocking” to Swift for-loop

纵饮孤独 提交于 2019-12-23 04:24:59

问题


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?

来源:https://stackoverflow.com/questions/28231913/add-blocking-to-swift-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!