Last active
September 15, 2015 12:04
-
-
Save darthpelo/ec25f9b9473649719342 to your computer and use it in GitHub Desktop.
Use reduce, in Swift 1.2, to filter a list of objects and create a array with objects with a specific property not nil. Based on an idea of Berik (https://github.com/berikv).
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
| let list: [String?] = [nil, nil, "ciao", "hello", nil] | |
| struct Obj { | |
| var group: [String?]? | |
| let name: String? | |
| } | |
| let o1 = Obj(group: list, name: "first") | |
| let o2 = Obj(group: nil, name: "second") | |
| let list2 = [o1, o2] | |
| list2.reduce([Obj]()) { | |
| if let e = $1.group { | |
| return $0 + [$1] | |
| } else { | |
| return $0 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment