functional programming - How to use swift flatMap to filter out optionals from an array -


i'm little confused around flatmap (added swift 1.2)

say have array of optional type e.g.

let possibles:[int?] = [nil, 1, 2, 3, nil, nil, 4, 5] 

in swift 1.1 i'd filter followed map this:

let filtermap = possibles.filter({ return $0 != nil }).map({ return $0! }) // filtermap = [1, 2, 3, 4, 5] 

i've been trying using flatmap couple ways:

var flatmap1 = possibles.flatmap({     return $0 == nil ? [] : [$0!] }) 

and

var flatmap2:[int] = possibles.flatmap({     if let exercise = $0 { return [exercise] }     return [] }) 

i prefer last approach (because don't have forced unwrap $0!... i'm terrified these , avoid them @ costs) except need specify array type.

is there alternative away figures out type context, doesn't have forced unwrap?

with swift 2 b1, can do

let possibles:[int?] = [nil, 1, 2, 3, nil, nil, 4, 5] let actuals = possibles.flatmap { $0 } 

for earlier versions, can shim following extension:

extension array {     func flatmap<u>(transform: element -> u?) -> [u] {         var result = [u]()         result.reservecapacity(self.count)         item in map(transform) {             if let item = item {                 result.append(item)             }         }         return result     } } 

one caveat (which true swift 2) might need explicitly type return value of transform:

let actuals = ["a", "1"].flatmap { str -> int? in     if let int = str.toint() {         return int     } else {         return nil     } } assert(actuals == [1]) 

for more info, see http://airspeedvelocity.net/2015/07/23/changes-to-the-swift-standard-library-in-2-0-betas-2-5/


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -