Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Last active August 29, 2015 14:21
Show Gist options
  • Save SlaunchaMan/897b55605f5c10763cf5 to your computer and use it in GitHub Desktop.
Save SlaunchaMan/897b55605f5c10763cf5 to your computer and use it in GitHub Desktop.
Optional Map
//: Playground - noun: a place where people can play
import Cocoa
/* If you’re doing something like parsing JSON, and you have an array of
dictionaries, optionalMap is nice to only parse *valid* model objects out of
the dictionary. It allows you to be type-safe while still discarding junk
data. */
extension Array {
func optionalMap<U>(transform: (T) -> U?) -> [U] {
var result: [U] = []
for item in self {
if let transformedItem = transform(item) {
result.append(transformedItem)
}
}
return result
}
}
struct foo: DebugPrintable {
let name: String
let id: UInt
init?(dictionaryRepresentation: [String: AnyObject]) {
if let name = dictionaryRepresentation["name"] as? String,
id = dictionaryRepresentation["id"] as? UInt {
self.name = name
self.id = id
}
else {
// There’s a bug in the Swift compiler that won’t let you return nil
// without initializing all required properties.
self.name = ""
self.id = 0
return nil
}
}
var debugDescription: String {
return "(Name: \(name), ID: \(id))"
}
}
let parsedJSON = [["name": "firstFoo", "id": 0], ["name": "secondFoo", "id": 1],
["name": "invalidFoo"]]
let validFoos = parsedJSON.optionalMap { foo(dictionaryRepresentation: $0) }
println(validFoos.debugDescription)
// Prints: [(Name: firstFoo, ID: 0), (Name: secondFoo, ID: 1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment