Using Optional Binding

I am currently reading “The Nil Coalescing Operator”. There is a program as below:

import UIKit

var errorCodeString : String?
errorCodeString = "404"
var errorDescription : String?

if let theError = errorCodeString, let errorCodeInteger = Int(theError), errorCodeInteger == 404 {

errorDescription = "\(errorCodeInteger + 200) : resource was not found."


var upCaseErrorDescription = errorDescription?.uppercased ()

upCaseErrorDescription?.append(“PLEASE TRY AGAIN”)

errorDescription = nil
let description: String
if let errorDescription = errorDescription {
description = errorDescription
} else {
description = “NO ERROR”

For this line:
if let errorDescription = errorDescription
errorDescription has been declared as variable since the beginning and declared again as constant here. I am confused here. Are these two “errorDescription” the same?
Appreciate your help. Thank you.

No the constant lives only in the if scope. It is quite confusing at first… I know!

How do you get the value of an optional out of an if loop? For example if the optional has a value and you unwrap this in the loop, how can you then get the value out of the loop to use later in your program?

You can use guard statement like:
guard let unwrappedOptional = optional else { continue or break or return }
// from now on you can use unwrappedOptional

Another solution:

let unwrappedOptional = optional ?? defaultValue

// from now on you can use unwrappedOptional