Unwrapping nested optionals

Overview

I have a nested optionals that I am trying to unwrap all at once.

Question

  1. Is there a nice way to unwrap nested optionals in one shot?
  2. I am using flatMap, just wondering if there is a nicer way to do it?

Code

Given below is sample code and my attempt to unwrap nested optionals.

func f1(p1: Int) {}

let n: Int?? = 1

// Is there a better way than to use flatMap?
if let n = n.flatMap({ $0 }) {
    f1(p1: n)
}
1 Like

You can use

if let n = n as? Int { ... }
4 Likes

@xAlien95 Thanks a lot that is really nice!!

Also,

if case let n?? = n {
  f1(p1: n)
}

if let n, let n {
  f1(p1: n)
}

n?.map(f1)
5 Likes

@Quedlinbug Thank you so much!!!

I remember seeing something to do with ? but completely forgot how to do it.

So happy to see this!!

1 Like

Just to throw another syntax in the ring:

if let n = n ?? nil { … }
1 Like