Skip to content

Instantly share code, notes, and snippets.

@ateliercw
Last active April 8, 2016 03:23
Show Gist options
  • Save ateliercw/e90357729ccdc53b1c17a3d8552aa902 to your computer and use it in GitHub Desktop.
Save ateliercw/e90357729ccdc53b1c17a3d8552aa902 to your computer and use it in GitHub Desktop.
Showing off using errors to speed up JSON decoding
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