Created
December 20, 2017 15:37
-
-
Save fitomad/3ddced4bb709b5f922dc3710d1958ba3 to your computer and use it in GitHub Desktop.
Example about Codable protocol in Swift 4
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 | |
// | |
// MARK: - Venue struct representation | |
// | |
/** | |
Different venue types. | |
*/ | |
public enum Kind: String, Codable | |
{ | |
case library | |
case shopping | |
case museum | |
case cinema | |
} | |
/** | |
And address representation | |
*/ | |
public struct Address: Codable | |
{ | |
public var street: String | |
public var number: Int? | |
public var city: String | |
/** | |
Set the JSON key values. | |
In `Address` json representation | |
`street` and `city` keys are named | |
in a different way. | |
*/ | |
private enum CodingKeys: String, CodingKey | |
{ | |
case street = "street_name" | |
case city = "city_name" | |
case number | |
} | |
} | |
/** | |
A venue | |
*/ | |
public struct Venue: Codable | |
{ | |
public var name: String | |
public var address: Address | |
public var kind: Kind | |
} | |
// | |
// MARK: - Encode | |
// | |
// | |
// Let's build Madrid Apple Store | |
// | |
let address: Address = Address(street: "Plaza de la Puerta del Sol", number: 1, city: "Madrid") | |
let appleStore: Venue = Venue(name: "Apple Store Madrid Flagship", address: address, kind: .shopping) | |
let encoder: JSONEncoder = JSONEncoder() | |
encoder.outputFormatting = .prettyPrinted // output looks pretty | |
if let data = try? encoder.encode(appleStore), let json = String(data: data, encoding: .utf8) | |
{ | |
print(json) | |
} | |
// | |
// MARK: - Decode | |
// | |
// | |
// Now simulate a HTTP request... | |
// | |
var jsonLibrary: String = """ | |
{ | |
"kind": "library", | |
"address": { | |
"city_name": "Madrid", | |
"street_name": "Calle de San Justo", | |
"number": 5 | |
}, | |
"name": "Biblioteca Pública Municipal Iván de Vargas" | |
} | |
""" | |
let decoder: JSONDecoder = JSONDecoder() | |
if let data = jsonLibrary.data(using: .utf8), let venue = try? decoder.decode(Venue.self, from: data) | |
{ | |
dump(venue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment