Wayne Filkins Wayne Filkins - 7 months ago 26
iOS Question

Is a for loop in a function completed before performing code after the function?

If I run this code:

fanoutObj = fanoutPost(followersList.uid, followers: followersSnap, post: post)

And the fanoutPost function has a really long for loop in it, then will will all the code in the function including the entire for loop be completed before the print(fanoutObj) runs?


The answer depends on the placement of the for loop:

  • If the for loop is in the body of the function directly, the answer is "yes", because all statements on the path to the end of the function or to the return statement must complete before the function returns.
  • If the for loop is in a closure which does not get called in the function itself, gets called asynchronously, or is executed on a separate queue, the answer is "no", because only the registration of the callback must complete, while the callback itself runs separately.

One simple way to find out is to use breakpoints or debug output to check the relative order of execution.