简体   繁体   English

解析Swift查询

[英]Parse with Swift queries

I am building an app that will handle voting for a talent show. 我正在开发一个可以处理选秀节目投票的应用程序。 I want to run a query that runs against a Parse database, and return the "Total". 我想运行一个对Parse数据库运行的查询,并返回“总计”。 Here's what I have: 这是我所拥有的:

 var query = PFQuery(className:"points")
    query.whereKey("Act", equalTo:"Act 1")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil
        {
            // The find succeeded.
            var test = objects["Total"]
            println(test)

            // Do something with the found objects
        } else {
            // Log details of the failure
            println("nope")
        }
    }

However when I run it, the console prints "Optional 3". 但是,当我运行它时,控制台会显示“ Optional 3”。 Any advice? 有什么建议吗?

Querying a dictionary always returns an optional, to handle the case when a key doesn't exist. 查询字典总是返回一个可选值,以处理键不存在的情况。

What you can do is apply the forced unwrapping operator ! 您可以做的就是应用强制展开操作符! :

var test = objects["Total"]!

but that generates a runtime exception if the key is not found. 但是,如果找不到密钥,则会生成运行时异常。 A better way is using optional binding: 更好的方法是使用可选绑定:

if let test = objects["Total"] {
    println(test)
}

The difference is that it is safer, and the if branch is executed only if objects["Total"] is not nil 区别在于它更安全,并且仅当objects["Total"]不为null时才执行if分支

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM