Swift Optional

Some people found it very confusing initially but when you will understand then it is simple. As we know optional tells itself about it. It's two cases.
  • The first case when a value can be present for a type, then we need to unwrap if need to use it.
  • Second case when a value can not be present for a type.
We use '?' to mark a value as optional.

class Student {
    var name:String? //  name becomes optional
}

When you declare the name string as optional by marking '?' then it's valued automatically is set to nil. 

NOTE: Swift 'nil' is not same as objective c 'nil'. In Objective-C, it is a pointer to an object which does not exist whereas in swift it's just an absence of a value for a type.

let person = Student()
print(person.name)

When you access the name it will print a nil. As there is no value assigned to name.
Once we will provide a value to name, let say, "Swift". Then it looks like.

class Student {
        var name:String? = "swift"
}

Now accessing the value of name using:

let person = Student()
print(person.name)

Will print the optional value. It will be like Optional("swift"). It's not the same as string "swift". It's type Optional and if you need to have this value then you use "Forced Unwrapping". Using '!', to read the optional value. But It's not recommended to use "!" to read an underlying value of Optional type it could be costly when the optional type does not have a value. Then it will crash your app. You can use whenever you want but you have to sure that Optional type has underlying value.

let person = Student()
print(person.name!) // will print "swift"

There are other ways to access the underlying value of optional type.
1 - Using If condition along with Forced Unwrapping: Use if condition to make sure, it has underlying value and reading using forced unwrapping '!'.

if person.name != nil {
        print(person.name!) // print "swift"
}

2- Using Optional Binding: You can use Optional binding to read the underlying optional value. You can access it and store it constant or variable type. Optional binding can be used with the "if" and "while".

if let temp = person.name {
        print(temp) // print "swift"
}

Optional binding is a safe way to handle optional. It won't make your app crash if the optional type does not have any value.
Hope I am able to make understand y'all. Please do comment and give your valuable feedback. 

Comments

Popular posts from this blog

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Copy Vs Mutable Copy in iOS

Functions in Swfit 3.0