• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Lifelong Learner

  • About
  • Portfolio

Optional binding and Optional Chaining

By Ravi Shankar 6 Comments

Swift has a feature that lets users to assign optional value to a variable or a constant. Optional variable or constant can contain a value or a nil value. Let us take the following example which tries to find a given string in a array of string.

Optional Binding

var fruits = ["Apple","Orange","Grape","Mango"] 
let searchIndex = fruits.firstIndex(of: "Apple")

The searchIndex would return value if the fruit exists or nil value if it doesn’t exist.

print("Fruit index is \(searchIndex)")

The proper way to handle this by using Optional binding method.

if let searchIndex = searchIndex {
 print("Fruit index is \(searchIndex)")
} else {
 print("Not available")
}

This would ensure only when searchIndex has a value the print with searchIndex gets executed.

Optional Chaining

Optional chaining is the way by which we try to retrieve values from a chain of optional values. Let us take the following example classes.

class School {
  var director:Person?
}

class Person {
var name: String = ""

init(name: String) {
    self.name = name
  }
}
var school = School()
var person = Person(name: "Jason")
school.director = person
school.director?.name

The director property in School class is optional, when you try to access subsequent values from director property becomes optional (? mark after director when accessing name property). You can handle these optionals as shown below.

if let name = school.director?.name {
  print("Director name is \(name)")
} else {
  print("Director yet to be assigned")
}

Filed Under: Apple, ios Tagged With: Apple, Optional bindings, Optional chaining, Swift

Reader Interactions

Comments

  1. james says

    January 3, 2018 at 11:29 am

    Nice work … Thankyou

    Reply
  2. Anilkumar says

    January 25, 2018 at 4:01 pm

    Nice explanation.

    Reply
  3. sravani says

    August 29, 2018 at 3:59 pm

    nice explanation thnq

    Reply
  4. Ganesh says

    November 4, 2018 at 4:19 pm

    Simple and straight explanation. Good!

    Reply
  5. Dharanikumar says

    December 17, 2018 at 6:50 am

    Nice Explanation

    Reply
  6. Ravi Prajapat says

    May 18, 2019 at 6:03 am

    Brilliant explanation.. Thanks!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

  • Email
  • LinkedIn
  • Twitter

iOS Cheat Sheets

Download free copy of iOS Cheat Sheets

Copyright 2023 © rshankar.com

Terms and Conditions - Privacy Policy