Skip to content

Instantly share code, notes, and snippets.

@StanislavK
Created February 25, 2018 16:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save StanislavK/e763cdc9fbe92f62f3c9dbd648e7e7ad to your computer and use it in GitHub Desktop.
Save StanislavK/e763cdc9fbe92f62f3c9dbd648e7e7ad to your computer and use it in GitHub Desktop.
extension Encodable {
func encode(with encoder: JSONEncoder = JSONEncoder()) throws -> Data {
return try encoder.encode(self)
}
}
extension Decodable {
static func decode(with decoder: JSONDecoder = JSONDecoder(), from data: Data) throws -> Self {
return try decoder.decode(Self.self, from: data)
}
}
@StanislavK
Copy link
Author

struct Language: Codable {
var name: String
var version: String
}

// create a new language
let language = Language(name: "Swift", version: "4")

// encode with one line of code
let data = try? language.encode()

let lang: Language? = try? Language.decode(from: data!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment