gpt4 book ai didi

swift - 初始化前被闭包捕获的变量

转载 作者:IT王子 更新时间:2023-10-29 05:04:10 26 4
gpt4 key购买 nike

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

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

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

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, 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
}

关于swift - 初始化前被闭包捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com