Swift Basics - Optionals

In Swift, nil is not a pointer to a non-existent object, it just means that it does not have a value.
var str: String? means that it might or might not have a value.

Optionals are used to deal with situations to avoid runtime errors in case variables have not been initialised. By declaring it as optional, we ensure that a variable's value is checked to not be nil being it is being used.

Unwrapping means to get a value from an optional.

Variables need to be a non-nil variable. They must always have a value.
If there are times when we need the variable to have a nil value, we can make use of optionals.
We can assign a nil value to an optional. We don't have to initialise it.
When we are retrieving a value from an optional, we need to make sure that it is not nil.

Here is how to declare an optional:
var nameOfString: String?
nameOfString = "ABC"
if nameOfString  != nil
{
  var newString = nameOfString! + "DEF"
}
Here are a few ways to unwrap an optional
Here is another way to check. We can assign it to another non-nil variable or constant:
This is known as optional binding:
var nameOfOptional: String?
if let nameOfConstant = nameOfOptional
{
 print(nameOfConstant)
}else
{
 print("This optional contains a nil value")
}

We can also do this:
var nameOfOptional: String?
if let nameOfOptional = nameOfOptional
{
 print(nameOfOptional)
}else
{
 print("This optional contains a nil value")
}

We can also use a variable:
var nameOfOptional: String?
nameOfOptional = "ABC"
if var nameOfOptional = nameOfOptional
{
 nameOfOptional = "DEF"
}

We can also force unwrap an optional:
var str: String?
str = "test"
var abc: String = str!

However, it is still be to check that the value is not nil.
if str != nil
{
 var abc = str!
}


Testing multiple optionals:
if let opt1 = opt1, let opt2 = opt2, let opt3 = opt3{//only when all 3 have non-nil values}

Calling methods, properties and subscripts of optional objects:

var sizeOfBed = house?.room?.bedSize
If either the house or the room contains a nil value, size of bed will be nil as well.

How to unwrap when there is optional chaining:
class ClassA{ var xyz: Int}
class ClassB{ var classA: ClassA?}
class ClassC{ var classB: ClassB?}
Optional binding:
if let tempB = classC.classB, let tempA = tempB.classA{}
OR
Below code is cleaner:
if let tempXYZ = classC.classB?.classA?.xyz{}

Nil Coalescing operator:
Use this when there is a default value in case the optional has a nil value:

var default = "ABC"
var optA: String?
var a = optA ?? default

Optional types:
var str: Optional<String>
is equivalent to:
var str: String?

How it is defined:
enum Optional<T>
{ case None
   case Some(T)
}
When case None - it means that there is no value. 
T is used to define a generic.

Comments

Popular posts from this blog

Setting up a playground

Go to another page