Swift 5.9 arrived with Xcode 15 and one of the new additions to the language is if-else and switch statements as expressions. SE-0380 proposed the new language feature, and we can find in depth information about it there. Let’s go through some of the examples where it comes handy.
Firstly, using if-else or switch for returning values in functions, closures or properties. I write quite a lot of code which just turns an enum value into some other type. Now we can omit the return statement which, in my mind, makes the code much more readable. Here we have an example of returning a different background colour based on the current coffee brewing method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Secondly, we can use this new feature for initializing variables with more complex logic without needing to create an immediately executing closure. Personally, I tend to do this quite a lot in my projects. Here is an example of assigning a value to the title variable based on the current brewing method. Note that we can omit return and the closure declaration now.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here is another example where we use if-else statement for the same purpose. Especially handy to contain some more complex logic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters