BSM

Mar 29 2020

Featuring:

HWS+

HWS+ is an all new service from Hacking With Swift. As of writing, it has 3 courses, which each have a few sections. Until WWDC, HackingWithSwift will publish a new section to one of the 3 courses every day, which afterwards will be every few days.
I can say, after watching all the videos that are released, that they are from really high quality(not only the resolution, also the content🙂!), and are really recommended if you want to level up in your swift and iOS development skills.
Once you are there, be sure to check out the other courses they have here


Closures: Returning values

Overview

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 questions@bdev-code.nl for any questions, feedback or if you just wanted to say hi.