Wednesday, May 13, 2015

Swift: the Unused Optional Value Problem

Natasha Murashev:

Here is a scenario – you need to do something in your code based on whether an optional value exists or not, but the thing you need to do does not need to actually use the optional value.

[…]

This immediately stood out as “wrong” to me. By now, I’m very well trained to unwrap optionals all the time, so having a != nil just feels wrong in Swift. Also, I don’t like the != here – I had to do a double take to realize that this code executes if something is actually there, so to me, it’s also not as readable. Of course, this code works and is completely “correct” for the situation, if that’s what you prefer.

David Owens II:

It just doesn’t feel semantically correct. The optional is not nil, it specifically has a value of None. I’ve never liked this syntax; I’ve talked about it before - thankfully the bool comparison has been lost, but the nil check still sits wrong with me.

Comments RSS · Twitter

Leave a Comment