Weird Swift Syntax 1 - Closures as function parameters

·

0 min read

Swift is an interesting language when it comes to syntax. It has some features that work very differently than in most languages.

Sometimes this can make Swift difficult to understand, especially for people who have in other languages before.

So I thought I would go over one of the interesting pieces of the language today: closures as function parameters.

If you've ever used JavaScript, it's likely that you have passed a function as a parameter to another function. For example:

myButton.addEventListener("click", function(event) {
    //Some code
});

Or, in ES6 syntax:

myButton.addEventListener("click",  (event) => {
    //Some code
});

This is a pretty common thing to do in JS. It turns out you can do this in Swift as well, but it looks a little different. Here's something like the equivalent of the above JS code in Swift:

myButton.addEventListener("click") { event in 
    //Some code
}

As you can see, the function argument has moved out of the parentheses enclosing the parameter list. If you're like me, the moment you saw this you went 🤯

Now, if you really hate this, you can put it back in like this:

myButton.addEventListener("click", { event in
    //Some code
});

Now, let's just break down this syntax real quick: The code is wrapped in braces ({}), and given the parameter event. Then we have the keyword in which you can think of as "putting" the parameter into the rest of the code.

So now that we understand how to pass a closure as a parameter, how do we define a function that accepts a closure?

In JS, we could just do this:

function addEventListener(eventType, callback) {
    //Some code...
    callback(event); //Run the callback
}

But Swift is a strongly-typed language, meaning we have to specify a type for the parameters. How do you define a closure type? I won't beat around the bush. Here it is:

func addEventListener( _ eventType: String, callback: (event: String) -> Void ) {
    //Some code...
    callback(event: event);
}

This is just saying that the callback parameter needs to be a function with an event parameter, which is a String, and the function needs to return Void (aka nothing).

So there you go, that's how we use closures as parameters in Swift!