Swift: Common mistakes no one bothers about — Optional force unwrap, vars and force cast IDAP Follow Jan 21, 2017 · 2 min read

Hello there, my sweet fellow developers,

In Swift, Apple introduced one really horrible thing, that breaks all the safety and sanity checks, as well, as eliminates usage of Optional as a safe type. This thing is the dark side of the force. It’s the operator !. I have several recommendations about using it:

Don’t use as!;

Don’t use variable!.doSomething();

Don’t use let variable: Type!.

Never use force operators;

Never ever use force operators;

You are not Jedi, don’t use force;

Neither are you a Sith, don’t use force;

Don’t, just don’t;

Kill everyone, who uses them, burn their houses and eat their kittens;

And more importantly, don’t you ever dare use them yourself.

The biggest problem with force operators is that Swift isn’t ObjC with its duck typing, where you could get away with using one object, as another one, if they have the same interface. It’s not nil-safe, like ObjC as well. You can’t send messages to nil in Swift, while in ObjC messages to nil return nil (it’s still unsafe for messages returning structs even in ObjC).

What this means is, that you will never be sure about your Swift code, if you use the force. You won’t be able to reason about it either. Even, if you are sure, that your code with the force operator would behave as expected, it could change the other day, when you forget and fail to provide the variable of proper type or proper value. The main reason behind using force is that the developer is too lazy to write proper well-structured predictable code. Overcome your laziness and don’t use force operators.

So, just remember, each time you use force in Swift, you don’t leave any choice to God. He has to kill at least a puppy and a kitten. So, be good to animals, don’t use force.

And, for the last time, let me stress once again:

DON’T USE FORCE OPERATORS

No exceptions

That’s all, folks. Have a great day and stay DRY, no matter, where you are.