Last active
October 5, 2019 02:32
-
-
Save chrismsimpson/f40e688509ed03329243d5541edad878 to your computer and use it in GitHub Desktop.
Codable extensions for Swift
This file contains 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 | |
extension Decodable { | |
public static func from(data: Data) throws -> Self { | |
return try JSONDecoder() | |
.decode(self, from: data) | |
} | |
} |
This file contains 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 | |
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