My thoughts on Closures in Swift

— 3 minute read

I recently started learning Swift via Paul Hudson's 100 days of SwiftUI. I am only on day 7 and so far I feel I have a fair handle on the concepts introduced so far. The initial topics like variables, constants, looping and data structures (Sets, Dictionaries and Tuples) were mostly straight-forward. The first topic in Swift that made me pause, re-read and think more is definitely Closures. Here are my thoughts on it.

  • The syntax for Closures in Swift feel weird, but I am happy that writing Javascript for several years has made me comfortable with the core concept.
  • Swift provides some nice code-readability aids such as being able to use two names for function parameters: one to be used inside the function and one to be used when the function is called. This really helps to make function calls read like plain English.
  • But it does favor code brevity over readability in other areas. For instance, I really like the idea of looking for (…) when reading code to understand that a function is being called. The opening and closing parenthesis serve as important markers/boundaries that signal the list of parameters that are sent to the function. The trailing closure syntax completely removes that visual hint and forces my brain to take a second stop at what’s going on when reading code. I am okay with this being an option in the language, I only wish that the trailing closure syntax is not as heavily used by the Swift community. I am just starting to learn Swift, so let’s see how this goes.
  • The shorthand functions that make the parameter type and the “return” keyword being optional reminds so much of JavaScript arrow functions. And yeah, I find the $0, $1 etc syntax for addressing parameters, totally unnecessary. The space saved by removing a few characters is so not worth the loss in clarity. My future self will thank me when reading code that is a little more explicit.
  • Returning closures from functions and immediately calling them feels so familiar. Thanks to JavaScript’s Immediatley invoked function expressions.
  • And finally, closures capturing values that are external to them, also reminds me of closures in JavaScript. Accessing variables created outside a function is a pretty common thing in JavaScript, although I tend to not rely on that too much.

How much of these features I will use and how I will use them, depends on the needs of the app I will be building. I tend to lean towards writing code that is a little less clever but a little more readable. But I do wonder how much of this structure will be dictated by the iOS platform and the libraries it provides.