本文介绍了在初始化之前由闭包捕获的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将查询的结果数存储为整数,以便可以使用它来确定表中的行数。但是,我收到以下错误:在行 query.findObjectsInBackgroundWithBlock {。

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{.

我还遇到另一个错误在初始化之前使用的变量'numberOfGames' 返回numberOfGames 。

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
    }


推荐答案

使用前需要初始化变量放在闭包中:

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

命令 var numberOfGames:Int 只需声明即可初始化即可,您可以使用 var numberOfGames = Int()或 var numberOfGames: Int = 0

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
    }

这篇关于在初始化之前由闭包捕获的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 20:57