我正在遍历整数对象并希望将每个整数添加到整数变量,然后当for循环完成时,打印总数。是否有捷径可寻?现在,我可以检索这些对象并单独打印它们,但每次总打印数为0。 请参阅下面的代码。这是一个用Swift和Parse编写的应用程序作为后端。 有帮助,谢谢!在for循环中添加整数并打印总数
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")
将'let itemsSum = ...'移动到'findObjectsInBackgroundWithBlock'中,并学习更多关于同步与异步函数的知识 –