Thursday, January 18, 2018

What are optional binding and optional chaining in Swift?

Optional bindings or chaining come in handy with properties that have been declared as optional. Consider this example:

class Student {
 var courses : [Course]?
}
let student = Student()


class Student {
 var courses : [Course]?
}
let student = Student()

Optional chaining
If you were to access the courses property through an exclamation mark (!) , you would end up with a runtime error because it has not been initialized yet. Optional chaining lets you safely unwrap this value by placing a question mark (?), instead, after the property, and is a way of querying properties and methods on an optional that might contain nil. This can be regarded as an alternative to forced unwrapping.

Optional binding
Optional binding is a term used when you assign temporary variables from optionals in the first clause of an if or while block. Consider the code block below when the property courses have yet not been initialized. Instead of returning a runtime error, the block will gracefully continue execution.

if let courses = student.courses {
  print("Yep, courses we have")
}

The code above will continue since we have not initialized the courses array yet. Simply adding:

init() { courses = [Course]() }

Will then print out "Yep, courses we have."