Mar 29 2020

Closures: Returning values


In the previous post, we saw how we can create closures, and how we can modify the behaviour of them using parameters. The next topic I want to touch on in closures is returning values. The reason why we would want to return values in closures is the following.

When you modify something, let’s say some text. Then you would want to do something with the modified text. If you would create a variable in your code that will hold the data you modified, and in the closure, you assign the modified text to that variable, it does the same thing. But, if you would return a value from the closure, that will save some lines of code because you don’t need to assign the value to the variable in the closure, but you can immediately assign the output of the closure to the variable.

You will do that as follows:

let myClosure = { (text: String) in
  return text.capitalized

let captilizedText = myClosure(text: "Hello world")

As you can see, it is a very short closure that contains only one line: return text.captilized. that takes the past in text, in our case "Hello world" and makes the first letter of each word capitalised. Then, because of the return keyword, swift automatically assigns the new text, the capitalized text, to the variable that calls it, in our case captilisedText. When you would add a print statement after you created the variable captilizedText to print that variable out, this should be the output:

"Hello World"

As you can see, it is not a lot of lines of code, especially when your only doing a small modification to, in our case, some text.

That was it! you finished the last (for now) article on closures!

I hope you know understand how closures work and how they can be used.

Don’t forget that you can email me at for any questions, feedback or if you just wanted to say hi.