Created
September 8, 2016 10:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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