Hallo allemaal, Leo hier. Today we will talk about one feature of the new Swift 5.9 that you can start to use now.
Before we start talking about code I need to say one word or two about the last events in my life.
First I was vacationing for 3 weeks in Brazil and I was one of the best men at my wife’s cousin’s wedding. The experience of going back to Brazil was full of emotions. While I was there, I was driving my mother-in-law’s car and I was involved in a not-dangerous car crash. The sound and the scare were the worst part and thankfully my wife and I are ok. We were waiting for the traffic light to become green when out of nothing a lady hit our car in the back. The good part is that neither of the people involved in the accident was harmed.
There we also visited a lot of friends and spend a lot of time with family in two different states of Brazil. Was an interesting trip.
After my three weeks trip, I went back to the Netherlands to start working at a new job. And I’m trying to learn everything that I can there, it has been amazing.
Because of that I’m a little late to write a new article but don’t worry, they will start to come again when I organize all the things that I need here.
Painting Of The Day
Today I chose a painting called A Portrait Of The Daughters Of Ramon Subercasseaux which is an 1892 oil painting by the Swedish artist Anders Zorn.
I chose it because the children are really young and in this new Swift update we have seen really fresh and young features of the language that we will be using for the next years and so.
Swift 5.9 – Macros, Non-Copyable, Macros
There’s a lot of fuzz in the community about Macros. I think they are great, however I want to discuss quickly some quirks about it.
The notable power of Swift’s macros lies in their ability to modify code at compile time dynamically. This feature can be leveraged to add additional functionality or automate repetitive tasks. Also, unlike traditional macros in languages like C++, Swift’s macros are type-safe. This level of type safety helps avoid many of the common pitfalls of macros in other languages, like inadvertent text replacement errors.
However, with these benefits come challenges. The complexity of macros can potentially lead to an increase in development and debugging time, especially for those new to the concept. Given that macros run as external programs during the build phase and operate in a sandbox, understanding their behavior and tracing their impact on code might not be straightforward.
Additionally, breaking down macros into multiple smaller types such as ExpressionMacro, AccessorMacro, and ConformanceMacro, while potentially useful for encapsulating specific behavior, might also add a layer of abstraction that could confuse less experienced developers.
The reliance on Apple’s SwiftSyntax library to manipulate source code introduces an additional dependency that developers must manage. While this is a powerful library for understanding and manipulating Swift code, it also adds to the potential learning curve and complexity of dealing with macros.
That all given, I personally feel that macros are something that I should give some time to rest within the community and see what happens. The potential is huge but also the struggles, and I personally will be conservative while adopting macros. Of course that in the future I want to write about them but now I don’t feel compelled to.
Completely changing the subjects, let’s talk about Copyables. First, look at the syntax:
struct PowerUser: ~Copyable { var fullName: String }
This affects enums and structs, and for me is different from everything that was already introduced in Swift language. Let’s dive into the problem the noncopyable types solve.
The key problem lies in how Swift handles unique its resources. Currently, Swift allows all types to be copyable, which may not be efficient or desirable for unique resources. While classes provide a kind solution passing by reference, they introduce their own set of issues such as heap allocation overhead, reference counting complexities, and shared ownership complications.
The proposal introduces a novel concept: noncopyable struct and enum types. These types would use a new ~Copyable syntax to suppress generic constraints, ensuring unique ownership and eliminating the issues associated with unnecessary copies or shared ownership. This could potentially lead to more efficient resource management and less complicated code, particularly where resources need to be managed uniquely.
A compelling aspect of this proposal is the introduction of deinit declarations for noncopyable structs and enums, a feature previously exclusive to classes. This would enable unique instances to execute certain operations at the end of their lifetimes, providing an additional level of control and efficiency.
The implications of this change for existing Swift codebases are not explored. It will be interesting to see how such a change might be introduced in a way that maximizes the existing Swift ecosystem expressivity.
The One New Feature that I Was Expecting The Most
I love Swift syntax sugars. For example, we can do things like this in Swift:
func doSomething() -> Bool { false }
This way you don’t need to explicitly put the return there because the Swift compiler is smart enough to do the work for you.
But what I don’t understand is why something like the code below was never possible:
func doSomething() -> Bool { // this function doesn't compile before Swift 5.9 switch Bool.random() { case true: true case false: false } }
But now Swift 5.9 and handles if and switch statements as expressions in several cases, which makes the code above work, that is so cool! Finally, we don’t need the return keywords when it is obvious that the returning value is the result of that expression.
The if statement now also gained new capabilities. Before if you wanted to write a one-line if statement you would need to use a ternary operator, check the code below:
let name = doSomething() ? "Leo" : "Ninha"
With Swift 5.9 you could rewrite the same thing using if statement:
let name = if doSomething() { "Leo" } else { "Ninha" }
This can be useless for the case above but imagine that you can now use the if statement as a return of functions too:
func leoOrNinha() -> String { if doSomething() { "Leo" } else { "Ninha" } }
That is so straightforward, I love that.
You can also use the switch statement as expressions on variables assignments:
let name = switch Bool.random() { case true: "Ninha" case false: "leo" } print(name)
The code above is totally valid in Swift 5.9.
Of course, some limitations apply to this new feature. For example, you cannot use it inside a default parameter for a function:
// This Doesn't compile!!! func leoOrNinha(name: String = if doSomething() { "Leo" } else { "Ninha" }) -> String { return name }
It shows an error saying:
‘if’ may only be used as expression in return, throw, or as the source of an assignment
And that is what I wanted to show you today peeps.
I’m slowly coming back to writing and I just installed the new Xcode 15 beta 2 and started to play with it, so don’t miss the the next articles that we will explore a lot of the new APIs, especially in SwiftUI.
And we are done!
Summary – The Most Exciting Swift 5.9 Feature
In conclusion, Swift 5.9 ushers in some compelling new features and improvements that enhance its flexibility, expressivity, and resource management.
The introduction of macros, while complex, holds potential for automatig repetitive tasks and adding functionality, provided developers navigate the intricacies with care.
The novel ~Copyable syntax for noncopyable struct and enum types provides a means to better manage unique resources, adding efficiency to codebases.
The newfound ability for if and switch statements to act as expressions brings with it a simplified, more intuitive syntax.
Fellow Apple Developers, that’s all.
I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or say hello on Twitter. I’m available on LinkedIn or send me an e-mail through the contact page.
You can likewise sponsor this blog so I can get my blog free of ad networks.
Thanks for the reading and… That’s all folks.
Image credit: Featured Painting