【发布时间】:2016-08-18 19:55:55
【问题描述】:
我正在循环遍历整数对象并希望将每个整数添加到一个整数变量中,然后当 for 循环完成时,打印总数。是否有捷径可寻?现在,我可以检索对象并单独打印它们,但每次总打印为 0。 请看下面的代码。这是针对以 Parse 作为后端的 Swift 编写的应用程序。 有什么帮助,谢谢!
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并了解有关同步与异步功能的更多信息
标签: ios swift loops parse-platform