Tuesday, December 6, 2016

What is Optional in Swift!!!

                       Apple's new programming language language swift is a very safe language. It will try to make sure that your code is not going to crash. To do this swift provides a feature called optional type. This optional type will store wrapped value if present and nil if no value presents. That basically means any optional variable either contains a value or nil. Lets see deep into optional type. The Optional type is a enumerated value with two values nil and some value which are represented as below.
  • Optional.none
  • Optional.some(value)
How to use optional: There  are two ways to  use - long form and short form. Mostly short form will be used, but we will see here both for better understanding purpose. Short form is represented by post question mark ?, and long form is represented by Optional key word.

let shortForm: Int? = Int("77")
let longForm: Optional = Int("77")

Optional Binding: We can use optional variable by unwrapping  the value, so that there wont be any runtime error. To unwrap conditionally we have three options
  • if let
  • gaurd let
  • switch
Optional Chaining: Optional chaining is a process for calling methods and properties on a optional that could be nil. if the optional contains a value, it will succeeds and proceeds for the next value, if the optional is nil, it simply returns nil. multiple optional method callings can be chained together and the entire chain will be failed gracefully if any one of the value is nil.

if let someResult = someValue?.someMethod()?.someAnotherMethod()
{
    print("Success")
} else {
    print("failed")
}
Nil-Coalescing Operator: This will be used for the optional to set default value for the nil optional value. And this can be used by doubel question mark ??. This can be also used as chaining

let someResult = someValue?? anotherValue

In this case, someResult will be someValue if it has value and anotherValue if someValue is nil.

Chaining example:
let someResult = someValue?? anotherValue?? anotherValue1

Unconditional Unwrapping: If you are sure that optional has a value,then this unconditional unwrapping will be used  by specifying  forced unwrap operator (postfix !). The problem with this feature is, if the optional value is nil, you will get run time error or possibly your app may crash.

let number = Int("77")!
print(number)
// Prints "77"

It is also possible to use chaining using postfix !.

let isPNG = imagePaths["image"]!.hasSuffix(".png")
print(isPNG)
// Prints "true"

Happy Swifting!!!

References:
Apple Doc

No comments:

Popular Posts