加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:37:26 所属栏目:百科 来源:网络整理
导读:我正在尝试将查询中的结果数存储到一个整数中,以便我可以使用它来确定表中的行数.但是,我收到以下错误:在初始化之前由闭包捕获的变量’numberOfGames’在行上query.findObjectsInBackgroundWithBlock {. 我还得到另一个错误变量’numberOfGames’在被初始化
我正在尝试将查询中的结果数存储到一个整数中,以便我可以使用它来确定表中的行数.但是,我收到以下错误:在初始化之前由闭包捕获的变量’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
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读