Closures

In Swift, a closure is a self-contained block of code that can be passed around and used in your code. You can pass a block of code as an argument to a function or method.

For example, a function could take two arguments: an Integer and a Closure. The closure argument could be a block of code which would be executed only if the integer is an even number.

A more common example is a “completion handler” in which the code in the closure is executed after some other asynchronous code is completed.

Imagine you want your app to reach out to an API and get data. When it is done getting that data you want that data to populate a view in your app. But you don’t know when it will be done getting the data, so a completion handler allows you to provide code the method which will be run when the task has completed.

By:


Leave a comment

Design a site like this with WordPress.com
Get started