Skip to content

Instantly share code, notes, and snippets.

@profburke
Created February 13, 2018 15:46
Show Gist options
  • Save profburke/842436afc6d876dd4ded557926a815b9 to your computer and use it in GitHub Desktop.
Save profburke/842436afc6d876dd4ded557926a815b9 to your computer and use it in GitHub Desktop.
use JSONDecoder on a string
import Foundation
enum ExtendedDecodingError: Error {
case badString
}
extension JSONDecoder {
public func decode<T>(_ type: T.Type, from string: String) throws -> T where T: Decodable {
if let data = string.data(using: .utf8) {
let result = try decode(type, from: data)
return result
} else {
throw ExtendedDecodingError.badString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment