Skip to content

Instantly share code, notes, and snippets.

@eMdOS
Last active April 23, 2019 15:04
Show Gist options
  • Select an option

  • Save eMdOS/88a465e8898a0600d0a343e148d6bef1 to your computer and use it in GitHub Desktop.

Select an option

Save eMdOS/88a465e8898a0600d0a343e148d6bef1 to your computer and use it in GitHub Desktop.
Codable {Apple Swift version 4.0 (swiftlang-900.0.45.6 clang-900.0.26)}
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)
}
}
@haashem
Copy link
Copy Markdown

haashem commented Jul 31, 2017

wonderful extension

sample code:

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!)

@rusher-R
Copy link
Copy Markdown

Wow!It's beautiful and simple code! Please accept my kness!

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