Ticker

6/recent/ticker-posts

Swift : Optionals (?&!)

Optionals (?&!):

Swift introduces the optionals, which manipulates the non-existence values. When the variable or object declared as optional one then it may have value or may be empty.


So optional object has priority of holding some value or none.


For example let's declared an optional object with help of '?'

        var language:String? = nil;

        var name:String? = "John Cena"

Let's print the above objects

        print("language is : \(language) and name is :\(name)")
        Out put : language is : nil and name is :Optional("John Cena")

Finally it prints optional results, but in the use case it should be a appropriate value. So in oder to get appropriate result we need to unwrap the value


To unwrap the appropriate value from optional object use '!' symbol.

  
Use the same print statement
         print("language is : \(language!) and name is :\(name!)")
Out put: fatal error: unexpectedly found nil while unwrapping an Optional value

So finally, while unwrapping the value of an object it should not be nil

         print("language is : \(language) and name is :\(name!)")
        Out put : language is : nil and name is :John Cena





Post a Comment

0 Comments