Swift Operator

! ? ?? what and how



Among the operators we use regularly on Swift these following three: ! ? ??, are most probably the most-used and most-confusing.  Most-confusing ! yes, because we didn’t spend enough time to have a complete understanding of these three. So let us drive deep.

Background:

Introduction

The Very first thing we need to know, is the name of those operators.
You ask why!!!
So that we can at-least talk about those operators with technical guy or gal on a technical talk. 😃

On this section we will find out the name and the usage of these three operators.
Why knowing usage is important?
Because these operators cloud have multiple functionality or usage based on there’s position and the operand they are operating.
If we know only one usage then, seeing the same operator on some different purpose/usage will make no/little scene to us. Whereas knowing all the usages of an operator, will make us confident about that operator and there will be no confusion on the different usage.

?? has a pretty simple name nil-coalescing operator. Ok not that simple yet, but will be once we start discussing on its functionality in the next section.
On Swift, nil-coalescing operator has only a single usage. And it is as nil-coalescing operator, more like setting a default value for a probable nil instance. Discussion is coming up on the next section.

On the other hand ! and ? have multiple usage on Swift.

On a regular bases ? will be addressed or named as Optional type.  Other than an Optional type, ? is also used as optional chaining and as ternary conditional operator . Again discussion coming up.

Now finally the most dangerous operator, !.
Why dangerous !!! We will find the reason on the end talk of this blog post on best practice to follow.
So ! is called as Force unwrapped operator . ! is also used on not equal operator, a != b , as binary operator. Another use of ! is as Logical NOT operator, !a, as Unary operator.

Enough naming talk 😠, Let us go to the real business now. 👀 

??nil-coalescing operator :

To understand the nil-coalescing operator lets observe an example

if optionalVar != nil{
    finalResult = optionalVar
}else{
    finalResult = defaultValue
}

?? as ternary conditional operator

Ahhh… the above code is ok, but we can make it better by using the ternary conditional operator as follows:

finalResult = optionalVar != nil ? optionalVar! : defaultValue

Side Note: ternary conditional operator are the operator that has three different parts. condition ? executeIfConditionTrue : executeIfConditionFalse. Swift has only one ternary operator. Mostly known as short-hand-if.

?? as nil-coalescing operator

Now we can even make it more elegant by using the nil-coalescing operator

finalResult = optionalVar ?? defaultValue

nil-coalescing operator tells the compiler that if the optionalVar, which is an Optionally-Typed-Variable, has a value then assign the value to finalResult. Otherwise assign it with the value of defaultValue , which is a Not-Optional-Typed-Variable/Constant.

So the function of nil-coalescing operator is to make sure it always provides a not-nil value.

Side Note: Optionally-Typed-Variable are the type of variable which cloud have either a value or a nil.

? Optional type operator:

Lets look at the following code:

let mayBeOrMayNotBe: Int?

We will read the mayBeOrMayNotBe as optional Int. The optional type operator, ?, tells the compiler that, mayBeOrMayNotBe can either have a value of Int or can have a nil.

So the functionality of optional type operator is to inform that this instance can either be nil or a proper instance.

? as Optional chaining operator

Optional chaining is one of the safest way of calling some method/property of an Optional type instance. If that instance is nil then no operation is done on that nil instance so the app does not crash. On the other hand if the instance is not nil then it will be operated. Let us look the the following Jedi example.

struct Jedi{
    let name: String?
    let age: Int
}

var yoda: Jedi?

yoda = Jedi(name: "Yoda", age: 900)
yoda?.name?.uppercased() //"YODA"
yoda?.age //900

yoda = nil
yoda?.name?.uppercased() //nil
yoda?.age //nil

We intentionally use the Optional Jedi so that we can set it to nil on later time.

yoda is an Optionally typed Jedi so we are using the Optional Chaining to safely getting the age property. The code does not crash even if we set yoda to nil.

Similarly as name is an optional string so to access the uppercased() method we are again using the Optional Chaining. The first ? of yoda?.name?.uppercased()  is for yoda: Jedi?. And the second ? is for name: String?

Thats how we are making a chain of  Optionally typed instances.

! Force unwrapped operator :

Well the usage of  Force unwrapped operator, !, is a key factor to identify if a Swift guy is new to Swift or not.
An advance Swift guy will never intensionally use the ! on his code unless he is absolute sure that it will have a value, probably just after initializing that instance. Let us find out the reason.

So first thing first. What is this operator. Like the name suggest.
The ! will force an Optionally typed instance to unwrapped itself. Now what can go wrong here !!! everything man!!!
The Optionally typed instance can be nil. And if so then unwrapping that instance will immediately crash the program, because of nil exception.

Lets modify the previous example by replacing the Optional Chaining ? with Force unwrapped operator !.

struct Jedi{
    let name: String?
    let age: Int
}

var yoda: Jedi?

yoda = Jedi(name: "Yoda", age: 900)
yoda!.name!.uppercased() //"YODA"
yoda!.age //900

yoda = nil
//yoda!.name!.uppercased() //Crashes the program
//yoda!.age //Crashes the program

On the first section when we are assigning yoda = Jedi(name: "Yoda", age: 300) we can use the Force unwrapped operator ! without having a crash and it gives the same result.  Because now yoda is a proper instance.
But when we assign yoda = nil and remove the commented-out code we will immediately have crash. Because now we are operating on a nil instance.

To be honest I also used to use the Force unwrapped operator.
But down on the path I understand why to avoid it, why not to autocorrect a statement using Force unwrapped operator when Xcode tells to fix it by Force-unwrap using.

When to Use:

Did we notice, all these three operators operates over possible-nil-instance aka Optionally typed. So whenever there is Optionally typed we will use one or two or all three of them.

Becoming Smart:

  • Don’t use Force unwrapped operator ! unless you are very very sure you will have the not-nil instance by the time of using the  Force unwrapped operator ! . 
    So best time to use  Force unwrapped operator ! is just after the initialization of an Optionally typed instance.
  • Always use Optional type operator ? to access the Optionally typed instance. Adopt the code so that it can always handle the optional type.
  • If it is bound to return some not-nil value, use the  nil-coalescing operator ? and provide a default value.

End talk:

On this blog post we concentrate on the usage of  ! ? ?? on a single domain and it is the  Optionally typed domain.

! and ? have some other use on Swift. We touch some of those domain here shortly.

The case study of HOF has some cool and practical usage of those operator. Visit and see these operator in real action.

Thanks, Happy Talks. 👊

Resources

One thought on “! ? ?? what and how

Leave a Reply

Notifications for mobidevtalk! Cool ;) :( not cool