somu
(somu)
1
Overview
I have a nested optionals that I am trying to unwrap all at once.
Question
- Is there a nice way to unwrap nested optionals in one shot?
- 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
xAlien95
(Stefano De Carolis)
2
You can use
if let n = n as? Int { ... }
4 Likes
somu
(somu)
3
@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
somu
(somu)
5
@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
bbrk24
6
Just to throw another syntax in the ring:
if let n = n ?? nil { … }
1 Like