Skip to content

Instantly share code, notes, and snippets.

@liweiz
Forked from griotspeak/JSONConvenience.swift
Created October 3, 2016 12:57
Show Gist options
  • Save liweiz/5196bbd0b993dd7520b859d533c3e1d3 to your computer and use it in GitHub Desktop.
Save liweiz/5196bbd0b993dd7520b859d533c3e1d3 to your computer and use it in GitHub Desktop.
Convenience overload for JSON parsing
import Foundation
extension JSONSerialization {
enum CastingError : Swift.Error {
case incompatibleType
}
static func jsonObject<T>(with data: Data, options: JSONSerialization.ReadingOptions) throws -> T {
let anyResult: Any = try jsonObject(with: data, options: options)
if let result = anyResult as? T {
return result
} else {
throw CastingError.incompatibleType
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment