Challenge: Finding base type of nested optionals

If you can accept an upper limit of say 10 levels of optionality, then I guess you could use something like the following (which is the same as this):

postfix operator …?
/// Unwraps 1 to 10 layers of `Optional`ity.
postfix func …?<T>(v: T??????????) -> T? { (v as? T?) ?? nil }

// Demo:
for _ in 0 ..< 3 {
  let a: Int?????? = Bool.random() ? 123 : nil
  let b: Bool? = Bool.random() ? true : nil
  let c: String???????? = Bool.random() ? "Hello" : nil
  let d: Float??? = Bool.random() ? 1.23 : nil
  let ua = a…?
  let ub = b…?
  let uc = c…?
  let ud = d…?
  print("--")
  print(type(of: ua), " | ", ua ?? "nil")
  print(type(of: ub), " | ", ub ?? "nil")
  print(type(of: uc), " | ", uc ?? "nil")
  print(type(of: ud), " | ", ud ?? "nil")
}

Not sure if it would be possible to express in some recursive way that would lift the upper limit.


I maintain that if you feel the need for something like this, then it is an indication of some deeper problem of your design.