Creating an extension to filter nils from an Array in Swift

前端 未结 7 658
难免孤独
难免孤独 2020-11-29 04:12

I\'m trying to write an extension to Array which will allow an array of optional T\'s to be transformed into an array of non-optional T\'s.

e.g. this could be writte

7条回答
  •  一生所求
    2020-11-29 04:24

    Since Swift 2.0 it is possible to add a method that works for a subset of types by using where clauses. As discussed in this Apple Forum Thread this can be used to filter out nil values of an array. Credits go to @nnnnnnnn and @SteveMcQwark.

    As where clauses do not yet support generics (like Optional), a workaround is necessary via a Protocol.

    protocol OptionalType {  
        typealias T  
        func intoOptional() -> T?  
    }  
    
    extension Optional : OptionalType {  
        func intoOptional() -> T? {  
            return self.flatMap {$0}  
        }  
    }  
    
    extension SequenceType where Generator.Element: OptionalType {  
        func flatten() -> [Generator.Element.T] {  
            return self.map { $0.intoOptional() }  
                .filter { $0 != nil }  
                .map { $0! }  
        }  
    }  
    
    let mixed: [AnyObject?] = [1, "", nil, 3, nil, 4]  
    let nonnils = mixed.flatten()    // 1, "", 3, 4  
    

提交回复
热议问题