【问题标题】:Adding integers in for loop and printing the total在 for 循环中添加整数并打印总数
【发布时间】: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


【解决方案1】:

试试这个:

var count = 0
...
for followingUser in followingUsersArray {
    count += object!["listedItems"] as! Int
}

【讨论】:

    【解决方案2】:

    您减少/组合Int 值的代码是正确的。问题是它在任何嵌套的异步 Parse 查询完成并执行其回调之前运行。所以在它运行的时候,itemsArray 仍然是空的。您将需要重新设计您的代码,以便仅在所有各种嵌套 Parse 查询全部完成后计算itemsSum

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多