Why did you use a closure as an argument of a function?

In Core Data by Tutorials Second Edition, Chapter 6, you used a closure as an argument to the traversePropertyMappings function.

Why is that? Was that for efficiency? Was there not a better way of writing the function?

Well one of the reasons for using closures is that you can handle everything insitu to make code look cleaner, more understandable. Having everything in one place also allows for you to handle memory issues better because you can save on creating globals for example.

That was supposed to be “insitu”. What does “insitu” mean?

Well normally you would process something in one class and maybe get it back in another function. You need to store that result in a variable to pass it to another function. Closures let you take the original data and send it to a function that will process the results and then immediately pass the instructions of what to do with the given results without having to go fetch the results yourself.

So for example:

object.saveInBackgroundWithBlock { (succeeded, error) -> Void in

//some code that will alert you if the save was successful or failed


Inside this block you are sending the instructions of what to do with whatever the result of the save actually was.