Variable captured by closure before being initialized

末鹿安然 提交于 2019-12-04 08:49:43

问题


I'm trying to store the number of results from a query into an integer so that I can use it to determine the number of rows in a table. However, I'm getting the following error: Variable 'numberOfGames' captured by a closure before being initialized' on the line query.findObjectsInBackgroundWithBlock{.

I also get another error Variable 'numberOfGames' used before being initialized on the line return numberOfGames.

Here's the function that contains the two errors:

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
    }

回答1:


You need to initialize the variable before use it inside a closure:

As per apple documentation

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.

The command var numberOfGames: Int just declare it to initialize you can use var numberOfGames = Int() or 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
    }


来源:https://stackoverflow.com/questions/30905038/variable-captured-by-closure-before-being-initialized

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