Use if/else and switch statements as expressions in Swift 5.9
Swift 5.9 brought an arsenal of enhancements to the already powerful and versatile language, but there's one in particular that has been long anticipated by developers. Swift now allows the use of if/else and switch statements as expressions, presenting an avenue to write more readable and concise code. This feature is a game-changer in initializing variables based on complex conditions without resorting to difficult-to-read ternary expressions.
If/Else Statements as Expressions
Consider the situation where you want to initialize a let
variable based on a complex condition. Traditionally, this would necessitate using compound ternary expressions that can quickly become convoluted. Here's an example of what that may look like:
Now, with Swift 5.9, you can leverage if/else expressions. This allows you to use a more familiar and readable chain of if statements. Below is the transformed code:
The updated code is considerably more readable and easier to follow, enhancing the overall maintainability of the codebase.
Global Variables and Stored Properties
The ability to use if/else and switch statements as expressions is particularly useful when initializing a global variable or a stored property. In previous versions of Swift, if your initialization required complex conditionals or switch statements, you would need to wrap them in a closure and execute it immediately, as shown:
Now, with the power of if expressions, you can simply eliminate that clutter, leaving you with much neater code:
Swift 5.9 brings a significant enhancement in readability and conciseness by allowing if/else and switch statements to be used as expressions. This can drastically improve your code structure, making it easier to read, understand, and maintain.
Happy coding!
XOXO,
Christian 👨🏻💻