Here is what I\'m trying to do:
extension Array> {
func unwrap() -> Optional> {
let a = self.flatMap
findall's solution works, although I think it's more readable to just avoid generics for this case:
func unwrap(optionalArray : [Element?]) -> [Element]? {
let unwrappedArray = optionalArray.flatMap { (a) -> [Element] in
switch a {
case Optional.Some(let x): return [x]
case Optional.None: return []
}
}
return unwrappedArray.count == optionalArray.count ? Optional.Some(unwrappedArray) : Optional.None
}
Usage:
let a = [Optional.Some(2), Optional.Some(3), Optional.Some(4)]
let b = [Optional.Some(1), Optional.None]
// Both are [Int]?
let unwrappedA = unwrap(a) // [2, 3, 4]
let unwrappedB = unwrap(b) // nil
See also: How to determine if a generic is an optional in Swift?