0

I have a 'while' loop that is checking Firebase for some prices on a menu. For each item, it goes to a specific ref URL and grabs that dish's price, then commits it's value to an array to be displayed on a table.

var i = 0
while i < self.itemNames.count {
  itemNameRef.childByAppendingPath("\(self.itemNames[i])/itemPrice").observeEventType(.Value, withBlock: {
    snapshot in
    self.itemPrices.append(snapshot.value as! String)
  })
  i++
}

Thing is, it seems to clear my entire array once it exits the observeEventType enclosure. I've placed some print() statements throughout the loop, and found that I can get it to print the array as it appends if the statement is directly beneath the appending code, but outside the }), it only returns an empty array.

What is going on here? Thanks!

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Joe Sloan
  • 775
  • 2
  • 9
  • 16

1 Answers1

4

What does the observeEventType method do?

From the fact that it takes a block/closure as a parameter, it suggests to me that it is an async function (A function that starts a long-running task on a background thread, then returns immediately, before the background task completes. Finally, it calls the completion block/closure when the long-running task completes.)

Analogy:

You are a college professor. You hand a stack of exams to your teaching assistant and say "Please grade these and enter the grades into the computer once you're done."

If, as your assistant walks towards an empty classroom to begin grading exams, you log into the your and check the exam grades, will they be entered? Of course not. The assistant hasn't even sat down yet!

The "go grade these exams" is the long-running task. The "And enter them into the computer once you're done" is the completion block/closure.

If you call an async function, then on the next line, look for the results, they won't be there.

You have to put code that runs once the task is completed inside the completion block/closure (Objective-C calls them blocks. Swift calls them closures. Other languages call them lambdas or anonymous functions.)

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I'm still confused, I guess. When I place my print statement directly underneath the appending code, it does print arrays with the proper data in them. It's just that it seems to actually clear data that was already there when exiting the loop. – Joe Sloan May 08 '16 at 16:19