Closure can be a difficult concept to grasp when you are starting Swift, it is common to come across code like var closure : () -> (), and what does () -> () here mean? is it a type? or could it be a function?

You might have seen traces of [weak self] before , what does this keyword mean? Somehow it have do with memory management, when should we use it?

You have probably used closure expression when calling API using URLSession dataTask function (the completionHandler), have you encountered any of the below?

Why do I get nil when I return the data from URLSession dataTask? I confirm that the json is retrieved!

Why do I get error unexpectedly found nil while unwrapping an Optional value when I return the data?

Wtf is It is expecting non-void return statement in void function ?!

It can be frustrating trying to get a value out of a closure expression, like using external variables and multiple boolean check to ensure that the data is retrieved. It doesn't have to be like this, once you understand how closure and asynchronous operation work, getting value out of a closure is as simple as using another closure (completion handler).


If you have been struggling with closures, give this email course a try!