Handling Optionals with 'if let' in Swift

January 18, 2019

Typically when you have an optional value of let's say type String?, in order to get the actual value you need to use you must unwrap them. We can achieve this by using if let or guard let.

Let's see this in action:

  var optionalString: String?
  if let s = optionalString {
      // if optionalString is not nil, the test evaluates to
      // true and s now contains the value of optionalString
  } else {
      // otherwise optionalString is nil and the if condition evaluates to false

Now what if your whole function needs it and not just the if block?

  var optionalString: String?
  guard let optionalString = optionalString else { return } 
 // optionalString can no longer be nil going forward.