Why Omitted return keywords made me love Swift 5.1
As we all know Xcode 11 beta comes packaged with Swift 5.1 which includes some of Apple’s new frameworks announced at WWDC 2019. SwiftUI, apple’s new UI Framework is one of the new frameworks that heavily relies on Omitted return keywords. Why would omitting the return word be such a big addition to the swift language. Well first off it makes it so that we can create code in a Reactive form, just like SwiftUI does. However my favorite reason is because we can now create small single line functions that look like methods. This makes the code look very clean. Below is an example of a function taking.advantage of omitting the return keyword.
This function getName returns My name without ever mentioning the keyword return. All we are passing in the braces is the returning string. This looks so nice compared to having a typical Swift 5 function that takes 4 formatted lines of code just to print the same thing. Yes you can do this in one line in Swift 5, but it does not look the same because we still have the return keyword in-between the. braces. At first this can look weird if you are not used to following the Swift evolution process, and learning about all the syntax changes. Once you start using this you will notice how much nicer it is to write a simple function. Here is the same function in one line with the return keyword. As you will see the return word looks out of place in a single line function.
Hopefully by now you are getting my point of why I love Swift 5.1 even more after using this feature. One appealing approach of omitting the return keyword is mathematical functions. They look like an actual equation instead of a equation with a return before it. This function will look like a very computer sciency type of code, but it looks to pretty compared to the old way of doing this.
The function above adds two values of type double, and then returns the result of the equation. This code looks so much cleaner especially when you think of doing a long equation that doesn’t need to declare anymore variables. For example creating a function that returns the result of a quadratic formula will look so much nicer because you just do the equation in-between the braces of the function using the variables inside the function parameters. This could potentially make complicated math look much nicer in code.