我试图将查询的结果数存储为整数,以便可以使用它来确定表中的行数。但是,我收到以下错误:Variable 'numberOfGames' captured by a closure before being initialized'行上的query.findObjectsInBackgroundWithBlock{

Variable 'numberOfGames' used before being initialized行上,我还收到另一个错误return numberOfGames

这是包含两个错误的函数:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        var user: PFUser!

        var numberOfGames: Int

        //...query code....removed to make it easier to read

        var query = PFQuery.orQueryWithSubqueries([userQuery, userQuery2, currentUserQuery, currentUserQuery2])
        query.findObjectsInBackgroundWithBlock{
            (results: [AnyObject]?, error: NSError?) -> Void in

            if error != nil {
                println(error)
            }

            if error == nil{

                if results != nil{
                    println(results)
                    numberOfGames = results!.count as Int
                }
            }
        }
        return numberOfGames
    }

最佳答案

您需要在闭包内部使用变量之前对其进行初始化:

As per apple documentation



只需将var numberOfGames: Int命令声明为初始化即可使用var numberOfGames = Int()var numberOfGames:Int = 0

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        var user: PFUser!
        var numberOfGames:Int = 0
        var query = PFQuery.orQueryWithSubqueries([userQuery, userQuery2, currentUserQuery, currentUserQuery2])
        query.findObjectsInBackgroundWithBlock{
            (results: [AnyObject]?, error: NSError?) -> Void in
            if error != nil {
                println(error)
            }
            if error == nil{
                if results != nil{
                    println(results)
                    numberOfGames = results!.count as Int
                }
            }
        }
        return numberOfGames
    }

10-08 01:05