Did you find this helpful? Why not support me to bring you even more content.
Click here to Buy Me a Coffee and say Thanks!

DISCLAIMER: This post is older than one year and maybe out of date.

Closures – The Basics

You maybe familiar with Closures from other languages, simply put they are blocks of code assigned to a variable. In this example we create a closure called welcome take note of the syntax in this example, it takes no arguments but returns a string. Then we simply call it like a function, try this in a playground and see what you get back, it should be “Hello!”

A closure can also be used as a parameter when calling a function, this may take a little getting used to if you have not spent any time with closures in other languages. This is an interesting example of Swift taking a look at what works in modern languages and adopting it for it’s own use. In the example below we call a function and give it a closure we want to execute in that function, this one simply returns a string.

There is a shortcut that can be taken here if the closure is the last argument, doing something called a ‘Trailing Closure’. To make this a little clearer and easier to understand I have added another parameter to the greeting function even though we do not use it.

In some situations you may find the code easier to read and follow using the trailing closure approach.

Link to Apple Swift Closures Documentation