What are Optionals in swift ?

from apple docs
//: Playground - noun: a place where people can playimport UIKitvar numberOfCrashes : Int?
print(numberOfCrashes!)
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?numberOfCrashes = 3print(numberOfCrashes!)
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?if numberOfCrashes != nil {print(numberOfCrashes!)}
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?if let crashCount = numberOfCrashes {print(crashCount) // same as print(numberOfCrashes!)}

Question: Well… wait..!! can we use if-var for optional binding???

var surveyAnswer: String?// surveyAnswer is automatically set to nil

Unwrapping optionals

— Forced unwrapping :

var myString:String?

myString = "Hello, Swift!"
let x = myString! // forced unwrapping Success!!!//_______________________________var myOtherString:String?

let x = myOtherString! // forced unwrapping Error. The value is not set.

— Implicit unwrapping :

let someString: String! 
print(someString) // risk for crash is high.
import UIKitclass Vehicle {var model: String!}var cars = Vehicle()print(cars.model) // it may crash the app sometimes. the value is nil.
var myString:String!

myString = "Hello, Swift!"
let x = myString // x is an optional string with value "Hello, Swift!"//_______________________________var myOtherString:String!

let x = myOtherString // x will be an optional string. The value is not set (or nil).

Forced vs implicit unwrapping :

let possibleString: String? = "An optional string."let forcedString: String = possibleString! // requires an exclamation mark_______________let assumedString: String! = "An implicitly unwrapped optional string."let implicitString: String = assumedString // no need for an exclamation mark

—Optional Binding :

if let constantName = someOptional {
//statements using 'constantName'
} else {
// the value of someOptional is not set (or nil).
}
let possibleNumber = "123" // a string  nonOptional constantif let actualNumber = Int(possibleNumber) {print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")} else {print("\"\(possibleNumber)\" could not be converted to an integer")}// Prints ""123" has an integer value of 123"
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")}// Prints "4 < 42 < 100"if let firstNumber = Int("4") {if let secondNumber = Int("42") {if firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")}}}// Prints "4 < 42 < 100"

Constants and variables created with optional binding in an if statement are available only within the body of the if statement. In contrast, the constants and variables created with a guard statement are available in the lines of code that follow the guard statement.

Digging deeper :

//: Playground — noun: a place where people can playimport UIKitclass Vehicle {var model: String?}
var car: Vehicle?
//: Playground — noun: a place where people can playimport UIKitclass Vehicle {var model: String?}var car: Vehicle?if let c = car {if let m = c.model {print(m)}}
if let c = car, let m = c.model {print(m)}
//: Playground — noun: a place where people can playimport UIKitclass Vechicle {var model: String?}var car: Vechicle?car = Vechicle() // created a new vehiclecar?.model = “Lamborgini”if let c = car, let m = c.model {
// only execute if car is valid and car has a valid model..
print(m)}
import UIKitclass Vehicle {var model: String?}var cars: [Vehicle]?cars = [Vehicle]()cars?.append(Vehicle()) // question mark in front of the dot is because it is an optional variable. if let carArray = cars, carArray.count > 0 {//execute only if cars array is valid and its count is greater than zero.
print(carArray.count)
}

Optional chaining :

let legs = House?.DiningRoom?.Chairs?.Legs?.first 
// just an example.. if chairs is nil, legs will be nil, if house is nil, chairs will obviously be nil and hence the legs..
import UIKitclass Human {var age: Intinit(age: Int) {self.age = age}}
class House {var human:Human?}
var houseObj = House()houseObj.human = Human(age: 10)
let ageOfHumanInHouse = houseObj.human?.age //ageOfHumanInHouse is optional Int

Its pretty simple.Lets assume that you saw a dream and you have a luxury house in your dream. The house in the dream is not real and you know that . So everything inside the house like a 100 inch curved LED tv , a lamborghini car in the garage , a luxury bed in the bedroom etc.. everything will be imaginary. It is just pure common sense.

if let ageOfHumanInHouse = ageOfHumanInHouse {print(“\(ageOfHumanInHouse)”)}

Important: Optionals don’t interact with each other. We have to unwrap an optional in order to do that.

What is the nil coalescing operator?

let name: String? = nil
let unwrappedName = name ?? "Anonymous"
let name: String? = nil
print("Hello, \(name ?? "Anonymous")!")

That’s it. !

If you enjoyed reading this post, please share and give some claps so others can find it 👏👏👏👏👏 !!!!

--

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Apache Kafka vs Amazon Kinesis to Build a High Performance Distributed System

My Contribution To DevOps Journeys 2.0

The Silo Factor: A Chaos Multiplier

The RPA hangover

Deploying a VPN server in Akash

Introduction to Helm: Part 01

CB Capital partners with SINSO Technology

Production Ready API Authorization Using Open Policy Agent (OPA)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhimuralidharan

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨

More from Medium

Closures in swift

A Swift transition

How it works Combine pipeline?

How to monitor progress of Xcode installation from App Store