Skip to content

Instantly share code, notes, and snippets.

@darthpelo
Created September 8, 2016 10:01
Show Gist options
  • Select an option

  • Save darthpelo/012293a1150ee1eae7a91bd34c6a770a to your computer and use it in GitHub Desktop.

Select an option

Save darthpelo/012293a1150ee1eae7a91bd34c6a770a to your computer and use it in GitHub Desktop.
How to perform map+filter in one command. Thanks to @nxsteveo @a2 & @nicklookwood
import Foundation
let a = [1,2,3,4,5]
let b = a.flatMap{ (i) -> (Int?) in
if i % 2 == 0 {
return i
} else {
return nil
}
}
func foo(bar: Int) -> Int? {
if bar % 2 == 0 {
return bar
} else {
return nil
}
}
let c = a.flatMap{foo(bar: $0)}
let d = a.filter{ i in
i % 2 == 0
}
func pippo(text: String) -> Int? {
if text.isEmpty {
return nil
} else {
return text.characters.count
}
}
let e = ["", "dog", "cat"].flatMap{pippo(text: String($0))}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment