swift – 被初始化之前由闭包捕获的变量

前端之家收集整理的这篇文章主要介绍了swift – 被初始化之前由闭包捕获的变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将查询中的结果数存储到一个整数中,以便我可以使用它来确定表中的行数.但是,我收到以下错误:在初始化之前由闭包捕获的变量’numberOfGames’在行上query.findObjectsInBackgroundWithBlock {.

我还得到另一个错误变量’numberOfGames’在被初始化之前在行上返回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

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.

命令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,error: NSError?) -> Void in
            if error != nil {
                println(error)
            }
            if error == nil{
                if results != nil{
                    println(results)
                    numberOfGames = results!.count as Int
                }
            }
        }
        return numberOfGames
    }

猜你在找的Swift相关文章