How to unwrap double optionals?

2 Solutions Collect From Internet About “How to unwrap double optionals?”

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 4 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"
}

Method 2:

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

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

Method 3:

Or you can use ?? with optional binding:

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

Method 4:

Also, you can use flatMap with optional binding:

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

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!!