我循环遍历整数对象并希望将每个整数添加到整数变量,然后在完成for循环时,打印总数。是否有捷径可寻?现在,我可以检索对象并单独打印它们,但每次打印总数为0。 请参阅下面的代码。这是一个用Swift编写的应用程序,Parse作为后端。 什么都有帮助,谢谢!
var itemsArray = [Int]()
let followingUserItemsQuery = PFUser.query()
followingUserItemsQuery?.whereKey("objectId", equalTo: (PFUser.currentUser()?.objectId!)!)
followingUserItemsQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error) in
if let objects = objects {
for object in objects {
let followingUsersArray = (object["following"] as! [String])
// Get number of listed items of following users with PFUser query for their total objects
for followingUser in followingUsersArray {
print(followingUser)
let query = PFUser.query()
query?.whereKey("objectId", equalTo: followingUser)
//Get each user's listedItems count then append to a higher-level integer variable
query?.getFirstObjectInBackgroundWithBlock({ (object, error) in
itemsArray.append(object!["listedItems"] as! Int)
})
}
}
}
let itemsSum = itemsArray.reduce(0, combine: +)
print(itemsSum)
self.followingUsersAddedItems.text = String("Your followers listed "+String(itemsSum)+" items")
答案 0 :(得分:1)
试试这个:
var count = 0
...
for followingUser in followingUsersArray {
count += object!["listedItems"] as! Int
}
答案 1 :(得分:1)
减少/合并Int
值的代码是正确的。问题是它在任何嵌套的异步Parse查询完成之前运行并执行它们的回调。所以当它运行时,itemsArray
仍然是空的。您需要重新设计代码,以便在所有各种嵌套的Parse查询都已完成后,仅计算itemsSum
。