Last active
April 8, 2016 03:23
-
-
Save ateliercw/e90357729ccdc53b1c17a3d8552aa902 to your computer and use it in GitHub Desktop.
Showing off using errors to speed up JSON decoding
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 | |
enum JSONDecodingError: ErrorType { | |
case NilValueForProperty | |
case TypeMismatch | |
} | |
extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject { | |
// Adds a Swift-y way to get a non-optional type from a key | |
func getValue<TypedReturn>(key: Key) throws -> TypedReturn { | |
guard let valueObject = self[key] else { | |
throw JSONDecodingError.NilValueForProperty | |
} | |
guard let value = valueObject as? TypedReturn else { | |
throw JSONDecodingError.TypeMismatch | |
} | |
return value | |
} | |
// Adds a Swift-y way to get a optional type from a key | |
func getOptionalValue<TypedReturn>(key: Key) throws -> TypedReturn? { | |
if let valueObject = self[key] where valueObject !== NSNull() { | |
guard let value = valueObject as? TypedReturn else { | |
throw JSONDecodingError.TypeMismatch | |
} | |
return value | |
} | |
return nil | |
} | |
} | |
let values: [String: AnyObject] = [ | |
"a": 2, | |
"b" :"Test", | |
"c": 4 | |
] | |
do { | |
let a: Int = try values.getValue("a") | |
} | |
catch { | |
error | |
} | |
do { | |
let b: Int = try values.getValue("b") | |
} | |
catch { | |
error | |
} | |
do { | |
let q: Int = try values.getValue("q") | |
} | |
catch { | |
error | |
} | |
do { | |
let q: Int? = try values.getOptionalValue("q") | |
} | |
catch { | |
error | |
} | |
do { | |
let b: Int? = try values.getOptionalValue("b") | |
} | |
catch { | |
error | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment