Skip to content

Instantly share code, notes, and snippets.

@darthpelo
Last active September 15, 2015 12:04
Show Gist options
  • Select an option

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

Select an option

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).
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