Skip to content

Instantly share code, notes, and snippets.

@stoeckley
Forked from erica/fun.swift
Last active August 29, 2015 14:24
Show Gist options
  • Save stoeckley/502ef711db3cee2ddff5 to your computer and use it in GitHub Desktop.
Save stoeckley/502ef711db3cee2ddff5 to your computer and use it in GitHub Desktop.
Start with an array of optionals and flat whack the heck out of 'em.
flatMap
let results = arrayOfOptionals.flatMap({$0})
for case
var results = [String]()
for case let value? in arrayOfOptionals {results.append(value)}
flatMap with (ugly) forced unwrap
let results = arrayOfOptionals.flatMap{$0 == nil ? [] : [$0!]}
map and append
var results = [String]()
arrayOfOptionals.map({
(optional : String?) -> Void in
if case let value? = optional {
results.append(value)}
})
for / guard
results = [String]()
for optional in arrayOfOptionals {
guard let unwrapped = optional else {continue}
results.append(unwrapped)
}
or worse:
results = [String]()
for optional in arrayOfOptionals {
do {
guard let value = optional else {throw NSError(domain:"", code:0, userInfo:nil)}
results += [value]
} catch {}
}
flatmap / map
// Thanks eridius
results = arrayOfOptionals.flatMap({ $0.map({[$0]}) ?? [] })
reduce / combine
// Thanks eridius
results = arrayOfOptionals.reduce([], combine: { $1 == nil ? $0 : $0 + [$1!] })
split / flat / flat
results = split(arrayOfOptionals, isSeparator: {$0 == nil}).flatMap({$0}).flatMap({$0})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment