Function Array> -> Optional>

前端 未结 3 1823
半阙折子戏
半阙折子戏 2021-01-06 09:12

Here is what I\'m trying to do:

extension Array> {   
  func unwrap() -> Optional> {
    let a = self.flatMap         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-06 09:51

    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?

提交回复
热议问题