我试图将查询的结果数存储为整数,以便可以使用它来确定表中的行数。但是,我收到以下错误:Variable 'numberOfGames' captured by a closure before being initialized'
行上的query.findObjectsInBackgroundWithBlock{
。
在Variable 'numberOfGames' used before being initialized
行上,我还收到另一个错误return 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
只需将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
}