Swift: Using Local Closures

Closures are often used as function arguments. But sometimes there are situations where local closures can be very handy.

Hint: This post has been updated to Swift 3, iOS 10 and Xcode 8
Imagine you have a view controller that has two GUI modes:

For each GUI mode you want to set some properties for three labels:

This is a lot of code. You could create a function that sets the properties for a label, but it is very unlikely that you will use that function ever again. So in this case it is a nice solution to define a local closure within the function:

It is short and it is nice.


Image: @ Sergey Nivens / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.