Assume we have an array of optionals defined:
var arrayOfOptionals: [String?] = [\"Seems\", \"like\", \"an\", nil, \"of\", \"optionals\"]
I
I took @Cenny's answer and decided to make an operator out of it:
prefix operator {}
prefix func (array: [T?]) -> [T] {
return array.filter{ $0 != nil }.map{ $0! }
}
I'm using it to parse an array of JSON objects and filter the ones that failed:
static func parse(j: JSONArray) -> [Agency]? {
return j.map { self.parse($0) }
}
Update for Swift 2+:
Use flatMap
operator and it'll only return non-nil objects