Kwok Wen Jian Kwok Wen Jian - 1 month ago 14
Swift Question

swift array not appending when in loop

I'm trying to retrieve data from Parse to append to my array of Groups:

var displayedGroups = [Groups]()


Groups is a struct:

struct Groups{
let name: String?
let date: Date
let number: Int
let id: String

init(id: String, name: String, date: Date, number: Int) {
self.id = id
self.name = name
self.date = date
self.number = number
}
}


this is the function that I try to retrieve data with:

func getDisplayedGroups() {
let query = PFQuery(className: "MeetUps")
print(PFUser.current()?.username)
query.whereKey("peeps", contains: PFUser.current()?.username)
query.findObjectsInBackground { (objects, error) in
if error != nil {
print(error)
} else if let objects = objects {
for meetUps in objects {
let peeps = (meetUps["peeps"] as! [String])
let id = meetUps.objectId!
//let name = meetUps["meetUpName"] as? String
let date = meetUps["when"] as! Date
let group = Groups(id: id, name: " ", date: date, number: peeps.count)
print(group)
self.displayedGroups.append(group)
}
}
}
for i in displayedGroups {
print(i)
}
tableView.reloadData()
}


I've commented out
let name = meetUps["meetUpName"]
... because there are nil values in my parse dashboard's "meetUpName"-key column.

print(group) works and it prints a different group for every loop.

however, this block:

for i in displayedGroups {
print(i)
}


doesn't print at all :/ and as such my table isn't loading data from displayedGroups. has it got to do with asynchronous? shouldn't be right? since they are in the same block. I have no idea, please advise. Thanks!

Answer

findObjectsInBackground works asynchronously, put the loop and the line to reload the table view in the completion block.

You might need to reload the table view on the main thread.

...
    for meetUps in objects {
      let peeps = (meetUps["peeps"] as! [String])
      let id = meetUps.objectId!
      //let name = meetUps["meetUpName"] as? String
      let date = meetUps["when"] as! Date
      let group = Groups(id: id, name: " ", date: date, number: peeps.count)
      // print(group)
      self.displayedGroups.append(group)
    }
    for i in displayedGroups {
      print(i)
    }
    dispatch_async(dispatch_get_main_queue) {
       self.tableView.reloadData()
    }
...
Comments