Swift Closures Learn by Obj-C examples

Swift closures and Objective-C Blocks

Let’s talk about Swift Closures and how to use them. When blocks were introduced in Obj-C it made life pretty awesome for developing clean self contained method. In swift, they’re called closures but they work the same, remember a block is just a block of code, and a closure is just a closure (i.e. { }) of code.

Examples

In this first example we’re defining a method that will upload something as an asynchronous request. When the upload is finished,we want to execute a block — or closure 😉 — of code.

In objective-c we’d define a method like this:

So we pass in an input variable something  and another variable named complete  that is the block of code defined as

(void(^)(Something * updatedSomething, NSError * error))

 

In swift the syntax is a lot neater so we can add a closure like this:

Great so now we can add closures to methods!

Let’s talk about creating a type alias so you can create multiple methods that pass the same block/closure. This is good for classes that use the same block / closure over and over again. Let’s look at the example:

If you want to define a type for this block, in Obj-C you’d do so like:

In swift, we can use typealias to give this swift closure a type name

Using this typealias in a function can now be used as:

Now when you want to run the closure in the function you will call it similarly to Obj-C like:




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *