How to unwrap double optionals?

Swift

Swift Problem Overview


How do you unwrap a string that is returned as:

> (Optional(Optional "blue"))

var cityName = String()
    
if let cityAnno = annotation as MGLAnnotation! {
    cityName = String(stringInterpolationSegment: cityAnno.title!)
}

cityLabelName.text = ("\(cityName), \(county)")

cityLabelName prints out as (Optional "New York")

Swift Solutions


Solution 1 - Swift

Given a double optional such as this doubly wrapped String:

let a: String?? = "hello"
print(a as Any) // "Optional(Optional("hello"))\n"

@Leo, showed that you could use optional binding twice:

if let temp = a, let value = temp {
    print(value) // "hello\n"
}

or force unwrap twice:

print(value!!)  // don't do this - you're just asking for a crash

Here are 5 more methods you can use to safely unwrap a double optional:

Method 1:

You can also use pattern matching:

if case let value?? = a {
    print(value) // "hello\n"
}

As @netigger noted in their answer, this can also be written as:

if case .some(.some(let value)) = a {
    print(value) // "hello\n"
}

which while less concise might be a bit easier to read.


Method 2:

Alternatively, you can use the nil coalescing operator ?? twice:

print((a ?? "") ?? "")  // "hello\n"

Note: Unlike the other methods presented here, this will always produce a value. "" (empty String) is used if either of the optionals is nil.


Method 3:

Or you can use the nil coalescing operator ?? with optional binding:

if let value = a ?? nil {
    print(value)  // "hello\n"
}

How does this work?

With a doubly wrapped optional, the value held by the variable could be one of 3 things: Optional(Optional("some string")), Optional(nil) if the inner optional is nil, or nil if the outer optional is nil. So a ?? nil unwraps the outer optional. If the outer optional is nil, then ?? replaces it with the default value of nil. If a is Optional(nil), then ?? will unwrap the outer optional leaving nil. At this point you will have a String? that is nil if either the inner or outer optional is nil. If there is a String inside, you get Optional("some string").

Finally, the optional binding (if let) unwraps Optional("some string") to get "some string" or the optional binding fails if either of the optionals is nil and skips the block.


Method 4:

Also, you can use flatMap with optional binding:

if let value = a.flatMap({ $0 }) {
    print(value)  // "hello\n"
}

Method 5:

Conditionally cast the value to the type. Surprisingly, this will remove all levels of optionals:

let a: String?? = "hello"
let b: String??????? = "bye"

if let value = a as? String {
    print(value)  // "hello\n"
}

print(b as Any)  // "Optional(Optional(Optional(Optional(Optional(Optional(Optional("bye")))))))\n"

if let value = b as? String {
    print(value)  // "bye\n"
}

Solution 2 - Swift

Try

var a:String?? = "1"
print((a))
if let b = a,c = b{
    print(c)
}

Screenshot of playground

enter image description here

Also you can force unwrap,but it it is not secure

let d = a!!

Solution 3 - Swift

I must say the accepted answer is very good, and I pefer method 1 from from that answer. However I'd like to use different syntax, making it a little more readable:

if case .some(.some(let value)) = a {
    print(value) // "hello\n"
}

Solution 4 - Swift

I've made a reduce() method on Optional to transform an Optional(Optional(U)) into an Optional(U) (like flatten() in Scala):

extension Optional {
    /// - Returns: Given an Optional(Optional(U)) returns an Optional(U)
    func reduce<U>() -> U? {
        switch self {
        case let unwrapped?:
            return unwrapped as? U
        default:
            return .none
        }
    }
}

To use it:

String example:

// By using reduce() you directly got a standard optional you can unwrap in the standard way (see answer of @vacawama above).
let aString: String? = Optional(Optional("Hello")).reduce()

let unwrapped = aString ?? "Default"

Int example:

// By using reduce() you directly got a standard optional you can unwrap in the standard way (see answer of @vacawama above).
let anInt: Int? = Optional(Optional(5)).reduce()

let unwrapped = anInt ?? 10

I mainly use it when I want to call a method which can throw an exception but for which in the current context I don't want to catch it. An example is reading a user property in the keychain:

let username: String = (try? keychain.get("username")).reduce() ?? "unknown"

Solution 5 - Swift

This is more of an important comment.

Think of a double optional as such:

indirect enum S {
  case value(s: S?)
  case none
}

While a normal optional is like this:

enum S {
  case value(s: S)
  case none
}

understanding why indirect is used in the first example is unimportant to scope of the question asked. It just doesn't compile without it! In the first example I was just trying to show that its internal type is also an optional type

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhil AndrewsView Question on Stackoverflow
Solution 1 - SwiftvacawamaView Answer on Stackoverflow
Solution 2 - SwiftLeoView Answer on Stackoverflow
Solution 3 - SwiftnetdiggerView Answer on Stackoverflow
Solution 4 - SwiftArtheynView Answer on Stackoverflow
Solution 5 - SwiftmfaaniView Answer on Stackoverflow