Coder Social home page Coder Social logo

flight-school / guide-to-swift-codable-sample-code Goto Github PK

View Code? Open in Web Editor NEW
237.0 11.0 17.0 93 KB

Xcode Playground Sample Code for the Flight School Guide to Swift Codable

Home Page: https://flight.school/books/codable

License: MIT License

Swift 100.00%
swift codable sample-code itunes-search userdefaults coredata messagepack

guide-to-swift-codable-sample-code's Introduction

Flight School Guide to Swift Codable Cover

Guide to Swift Codable Sample Code

Build Status License Swift Version

This repository contains sample code used in the Flight School Guide to Swift Codable.


Chapter 1

Chapter 1 introduces Codable by way of a round-trip journey --- going from model to JSON representation and back again.

Plane

let json = """
{
    "manufacturer": "Cessna",
    "model": "172 Skyhawk",
    "seats": 4,
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let plane = try! decoder.decode(Plane.self, from: json)

Chapter 2

Chapter 2 follows a more complicated example with nested structures, mismatched keys, and timestamps.

Flight Plan

let json = """
{
    "aircraft": {
        "identification": "NA12345",
        "color": "Blue/White"
    },
    "route": ["KTTD", "KHIO"],
    "departure_time": {
        "proposed": "2018-04-20T15:07:24-07:00",
        "actual": "2018-04-20T15:07:24-07:00"
    },
    "flight_rules": "IFR",
    "remarks": null
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

let plan = try! decoder.decode(FlightPlan.self, from: json)

Chapter 3

Chapter 3 shows what to do when Codable conformance can’t be synthesized by the compiler.

In the process, we share an implementation of a type-erased AnyCodable type.

AnyDecodable

struct Report: Decodable {
    var title: String
    var body: String
    var metadata: [String: AnyDecodable]
}

Coordinates

let json = """
{
    "coordinates": [
        {
            "latitude": 37.332,
            "longitude": -122.011
        },
        [-122.011, 37.332],
        "37.332, -122.011"
    ]
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let coordinates = try! decoder.decode([String: [Coordinate]].self, from: json)["coordinates"]

EconomySeat

class EconomySeat: Decodable {
    var number: Int
    var letter: String
    // ...
}

class PremiumEconomySeat: EconomySeat {
    var mealPreference: String?
    // ...
}

let json = """
{
    "number": 7,
    "letter": "A",
    "mealPreference": "vegetarian"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let seat = try! decoder.decode(PremiumEconomySeat.self, from: json)

EitherBirdOrPlane

let json = """
[
    {
        "type": "bird",
        "genus": "Chaetura",
        "species": "Vauxi"
    },
    {
        "type": "plane",
        "identifier": "NA12345"
    }
]
""".data(using: .utf8)!

let decoder = JSONDecoder()
let objects = try! decoder.decode([Either<Bird, Plane>].self, from: json)

FuelPrice

protocol FuelPrice {
    var type: Fuel { get }
    var pricePerLiter: Double { get }
    var currency: String { get }
}

struct CanadianFuelPrice: Decodable {
    let type: Fuel
    let price: Double /// CAD / liter
}

extension CanadianFuelPrice: FuelPrice {
    var pricePerLiter: Double {
        return self.price
    }

    var currency: String {
        return "CAD"
    }
}

Pixel

let encoder = JSONEncoder()
encoder.userInfo[.colorEncodingStrategy] =
    ColorEncodingStrategy.hexadecimal(hash: true)

let cyan = Pixel(red: 0, green: 255, blue: 255)
let magenta = Pixel(red: 255, green: 0, blue: 255)
let yellow = Pixel(red: 255, green: 255, blue: 0)
let black = Pixel(red: 0, green: 0, blue: 0)

let json = try! encoder.encode([cyan, magenta, yellow, black])

Route

let json = """
{
    "points": ["KSQL", "KWVI"],
    "KSQL": {
        "code": "KSQL",
        "name": "San Carlos Airport"
    },
    "KWVI": {
        "code": "KWVI",
        "name": "Watsonville Municipal Airport"
    }
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let route = try decoder.decode(Route.self, from: json)

Chapter 4

Chapter 4 is a case study in which you build search functionality for a music store app using the iTunes Search API (but really, it’s a lesson about command-line tools and epistemology).

We also released AppleiTunesSearchURLComponents as a standalone component.

Music Store

viewController.search(for: Music.self, with: <#artist#>)

Chapter 5

Chapter 5 shows you how to use Codable with UserDefaults by way of an example app for tabulating in-flight snack orders.

In Flight Service

guard let url = Bundle.main.url(forResource: "Inventory", withExtension: ".plist") else {
    fatalError("Inventory.plist missing from main bundle")
}

let inventory: [Item]
do {
    let data = try Data(contentsOf: url)

    let decoder = PropertyListDecoder()
    let plist = try decoder.decode([String: [Item]].self, from: data)
    inventory = plist["items"]!
} catch {
    fatalError("Cannot load inventory \(error)")
}

Chapter 6

Chapter 6 is about how Codable fits into a Core Data stack. The example app for this chapter is a luggage tag scanner that reads JSON from QR codes.

Luggage Scanner

do {
    for image in tagsAtDeparture {
        try scanner.scan(image: image, at: .origin, in: context)
    }

    try context.save()
} catch {
    fatalError("\(error)")
}

Chapter 7

Chapter 7 is a doozy. It walks through a complete implementation of a Codable-compatible encoder for the MessagePack format, from start to finish.

A complete Codable-compliant implementation is available at Flight-School/MessagePack. If you're interested in building your own Codable encoder or decoder, check out our DIY Kit.

MessagePackEncoder

let plane = Plane(manufacturer: "Cirrus",
                  model: "SR22",
                  seats: 4)

let encoder = MessagePackEncoder()
let data = try! encoder.encode(plane)

License

MIT

About Flight School

Flight School is a book series for advanced Swift developers that explores essential topics in iOS and macOS development through concise, focused guides.

If you'd like to get in touch, feel free to message us on Twitter or email us at [email protected].

guide-to-swift-codable-sample-code's People

Contributors

davidskeck avatar mattt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

guide-to-swift-codable-sample-code's Issues

Supporting Arrays in Ch. 7

The following:
struct Planes: Codable {
var planes: [Plane]
}

let planes = [plane]
let e = MessagePackEncoder()
let d = try! e.encode(planes)

print(d.map{ String(format:"%2X", $0) })

result in ["90"]

I don't see nested containers are supported. Am I missing something?

only superclass keys are encoded

This is regarding chapter 7 playground MessagePackEncoder.
Where's my class info 🙂 ?

class PlaneClass: Encodable {
var manufacturer: String = "Cirrus"
var model: String = "SR22"
var seats: Int = 4
}

class Boeing: PlaneClass {
var engine: String = "ENGINE1"
}

var plane1 = Boeing()

let classencoder = MessagePackEncoder()
let data1 = try! classencoder.encode(plane1)

print(data1.map { String(format:"%02X", $0) })

Only superclass keys are encoded...
Expected Boeing class engine key to be encoded.
both playground and this code encodes same keys:

Playground(struct) code:

"encoding" CodingKeys(stringValue: "manufacturer", intValue: nil)
"encoding" CodingKeys(stringValue: "model", intValue: nil)
"encoding" CodingKeys(stringValue: "seats", intValue: nil)
["83", "A5", "73", "65", "61", "74", "73", "04", "A5", "6D", "6F", "64", "65", "6C", "A4", "53", "52", "32", "32", "AC", "6D", "61", "6E", "75", "66", "61", "63", "74", "75", "72", "65", "72", "A6", "43", "69", "72", "72", "75", "73"]

My code:

"encoding" CodingKeys(stringValue: "manufacturer", intValue: nil)
"encoding" CodingKeys(stringValue: "model", intValue: nil)
"encoding" CodingKeys(stringValue: "seats", intValue: nil)
["83", "AC", "6D", "61", "6E", "75", "66", "61", "63", "74", "75", "72", "65", "72", "A6", "43", "69", "72", "72", "75", "73", "A5", "6D", "6F", "64", "65", "6C", "A4", "53", "52", "32", "32", "A5", "73", "65", "61", "74", "73", "04"]
nil

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.