Skip to content

Instantly share code, notes, and snippets.

@chrismsimpson
Last active October 5, 2019 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismsimpson/f40e688509ed03329243d5541edad878 to your computer and use it in GitHub Desktop.
Save chrismsimpson/f40e688509ed03329243d5541edad878 to your computer and use it in GitHub Desktop.
Codable extensions for Swift
import Foundation
extension Decodable {
public static func from(data: Data) throws -> Self {
return try JSONDecoder()
.decode(self, from: data)
}
}
import Foundation
extension Encodable {
public func toData() throws -> Data {
return try JSONEncoder()
.encode(self)
}
public func toString(with encoding: String.Encoding = .utf8) throws -> String? {
let data = try self.toData()
return String(data: data, encoding: encoding)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment