Created
May 31, 2018 13:57
-
-
Save shankartshinde/9a67fd175b4154a0a8e1a7726a1cd4cd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import Foundation | |
struct Swifter { | |
let fullName: String | |
let id: Int | |
let twitter: URL | |
init(fullName: String, id: Int, twitter: URL) { // default struct initializer | |
self.fullName = fullName | |
self.id = id | |
self.twitter = twitter | |
} | |
} | |
extension Swifter: Decodable { | |
enum MyStructKeys: String, CodingKey { // declaring our keys | |
case fullName = "fullName" | |
case id = "id" | |
case twitter = "twitter" | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: MyStructKeys.self) // defining our (keyed) container | |
let fullName: String = try container.decode(String.self, forKey: .fullName) // extracting the data | |
let id: Int = try container.decode(Int.self, forKey: .id) // extracting the data | |
let twitter: URL = try container.decode(URL.self, forKey: .twitter) // extracting the data | |
self.init(fullName: fullName, id: id, twitter: twitter) // initializing our struct | |
} | |
} | |
let json = """ | |
{ | |
"fullName": "Federico Zanetello", | |
"id": 123456, | |
"twitter": "http://twitter.com/zntfdr" | |
} | |
""".data(using: .utf8)! // our native (JSON) data | |
let myStruct = try JSONDecoder().decode(Swifter.self, from: json) // decoding our data | |
print(myStruct) // decoded! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment