Blocks/Closures are confusing! They’re confusing because its a bit abstract. Most tutorials cover how a block is declared and used.
Sometimes blocks or closures can me even more confusing…
A block is a bunch of code wrapped up in a {}.
You can 2 either of 2 things with them:
A. You can assign that block of code to a variable. (this is where completionHandlers, also a confusing concept, fit in)
B. You can use that block of code directly
Let’s take a look at assigning it to something. No doubt you have seen a construct like:
var someName = “Mars”
or
var hisAge = 39
This would be considered hardcoding that value to the variable.
Now surely you have seen a function that does something more practical such as calculate or do something in order to return a value. In the case of someName, well, we could fetch it from a list of users in a web service database. In the case of hisAge we could calculate it. Either process would occur in a function. So we could instead of hardcoding a value, say:
var someName = getHisName()
or
var hisAge = getHisAge()
Well what we are doing here is actually ‘passing a block of code’ to a variable already. Sorta. We could somehow imagine that:
var hisAge = getHisAge() { //all the code inside getHisAge function }
which translates to:
var hisAge = { //all the code inside getHisAge function }
Ok, so that’s more or less what a block or closure is.
Where it gets weird, or complicated but just because of the way it looks is when they are passed to functions. You could go ahead and say something like:
func thisIsSomeFunction () -> () { //code }
which is a function that doesn’t take parameters and returns nothing. Let’s give it a parameter:
func thisIsSomeFunction (aParameter:pType) -> () { //code }
This takes aParameter of pType. Now replace that parameter with hisAge:
func thisIsSomeFunction (hisAge) -> () { //code}
Now let’s replace hisAge for what it stands for (which is { //all the code inside getHisAge function } )
func thisIsSomeFunction ( () -> () ) -> () { //code}
where () -> () stands for whatever hisAge is equal to, which is the getHisAge function…
Of course the getHisAge function must at least return something, an age, which would typically be an Int:
func thisIsSomeFunction ( () -> (Int) ) -> () { //code }
It would be wise to calculate someone’s age using at least his date of birth, so:
func thisIsSomeFunction ( (NSDate) -> (Int) ) -> () { //code }
Ok so our getHisAge function is in blue and it is passed into this new function. Now it would be nice to pass in the original getHisAge code which would fit somewhere in here:
func thisIsSomeFunction ( (NSDate) -> (Int) {//getHisAge code} ) -> () { //code }
So for this purpose we have the keyword “in”:
func thisIsSomeFunction ( (NSDate) -> (Int) in {//getHisAge code} ) -> () { //code }
Hope you enjoyed it. See you in the next part!