Some APIs are more dangerous than they seem 🫢
Hi 👋
Last week has been quite intense for me: I attended the Paris iOS conference, where I gave both a talk about Parameter Packs and workshops on Swift Macros 🇫🇷
The talk was recorded and a replay should be available soon 😀
(and for the macros workshop, I plan on hosting a new session on YouTube later this year)
My next conference is planned for November, so I’m going to enjoy the coming weeks to chill and relax 😌
But don’t worry, I still have cool content planned, like a new livestream no later than this Thursday!
And now, before we go into the topic of this email, I have a big thank you to my sponsor this week: Bitrise 🤖
Advertisement
Sponsors like Bitrise really help me grow my content creation, so if you have time please make sure to have a look at the event they’re organizing: it’s a direct support to my content creation ☺️
Last week, I ran this poll on Twitter and LinkedIn:
As you can see, out of almost 500 votes, a short majority was thinking that the call to the method .removeLast()
would return nil
.
But of course, I asked that question because there is definitely something more to it than what seems to be the straightforward answer 🙃
As it turns out, Swift offers two different methods to remove the last element of an Array: we can use either .popLast()
or .removeLast()
.
If we look at their respective documentation, we can see that both methods are extremely similar, save for a small difference 🤨
Can you spot that difference?
As you’ve probably realized, the difference lies in the return type:
.popLast()
returns an optional.removeLast()
returns a non-optional
With that information, it becomes easier to figure out the correct answer!
Since the Array
is empty, .removeLast()
won’t be able to return a value and so its only possible outcome at that point will be to crash 💥
This behavior is actually hinted at later down in the documentation of .removeLast()
, but without explicitly mentioning the risk of crashing:
So why did I choose to ask this question in the first place?
I asked this question because as Swift developers we are usually aware that a number of operations can be dangerous, such as:
force unwrapping a
nil
valuesubscripting an
Array
outside its boundsusing one of the many APIs with
unsafe
in their name
However, in the case of .removeLast()
, if you don’t already know the risk, it is very easy to overlook it. (both when writing or reviewing the code)
That’s why I figured that this example was a nice reminder of the importance of trying as often as possible to test our code at its edge cases: this way we can detect issues before they sneak their way into production 💥
That’s all for this email, thanks for reading it!
If you’ve enjoyed it, feel free to forward it
to your friends and colleagues 🙌
I wish you an amazing week!
❤️