Skip to content

Instantly share code, notes, and snippets.

@erica
Last active August 29, 2015 14:24
Show Gist options
  • Save erica/6322a240539675edcbe5 to your computer and use it in GitHub Desktop.
Save erica/6322a240539675edcbe5 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})
filter / map
results = arrayOfOptionals.filter({$0 != nil}).map{$0!}
recurse
func squeezle(var arrayOfOptionals : [String?]) -> [String] {
if arrayOfOptionals.isEmpty {return []}
if let last = arrayOfOptionals.removeLast() {
return squeezle(arrayOfOptionals) + [last]
} else {return squeezle(arrayOfOptionals)}
}
results = squeezle(arrayOfOptionals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment