Challenge: Flattening nested optionals

Well done, that was quick!

I posted this puzzle because I only just figured out how to do it yesterday, after having previously tried unsuccessfully some months ago.

The solution I had in mind is very similar to @gwendal.roue’s, though singly-recursive rather than bouncing between two functions:

protocol Flattenable {
  func flattened() -> Any?
}

extension Optional: Flattenable {
  func flattened() -> Any? {
    switch self {
    case .some(let x as Flattenable): return x.flattened()
    case .some(let x): return x
    case .none: return nil
    }
  }
}
1 Like