Variable Scope

In the taxi pulsing example, you might have noticed something strange about the animation block. It uses pulseAmount, spaceAmount, and self. But how? If this were a function, each of those would need to be an argument. But the block takes no arguments.

This is one of the very powerful features of blocks. They have access to all the variables at the point where they were created. That is, they pull in all the variables from the current scope. One way to think about this is that they have access to the same variables that a line of code in exactly the same position would have. If you have used languages like Smalltalk and Lisp, you can think of blocks as closures.

Try the following example by adding the code to viewDidLoad for any ...

Get Learning iOS Development: A Hands-on Guide to the Fundamentals of iOS Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.