All Projects → Flight-School → Guide To Swift Codable Sample Code

Flight-School / Guide To Swift Codable Sample Code

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

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to Guide To Swift Codable Sample Code

Widgetexamples
A demo project showcasing different types of Widgets created with SwiftUI and WidgetKit.
Stars: ✭ 125 (-42.66%)
Mutual labels:  userdefaults, coredata
AC-iOS-Codeable-and-UserDefaults
No description or website provided.
Stars: ✭ 16 (-92.66%)
Mutual labels:  userdefaults, codable
Swiftdb
A modern database abstraction layer, batteries included.
Stars: ✭ 183 (-16.06%)
Mutual labels:  coredata, codable
Userdefaultsstore
Why not use UserDefaults to store Codable objects 😉
Stars: ✭ 416 (+90.83%)
Mutual labels:  userdefaults, codable
Messagepack
A MessagePack encoder and decoder for Codable types
Stars: ✭ 167 (-23.39%)
Mutual labels:  messagepack, codable
Persistentstorageserializable
Swift library that makes easier to serialize the user's preferences (app's settings) with system User Defaults or Property List file on disk.
Stars: ✭ 162 (-25.69%)
Mutual labels:  userdefaults
Securedefaults
A lightweight wrapper over UserDefaults/NSUserDefaults with an additional layer of AES-256 encryption
Stars: ✭ 179 (-17.89%)
Mutual labels:  userdefaults
Coredata Crud Swift 5.0 Example
Swift 5.0 Example project that exposes the usage of Core Data to create Entities and to persist to a SQLite Datastore
Stars: ✭ 157 (-27.98%)
Mutual labels:  coredata
Ladybug
A powerful model framework for Swift 4
Stars: ✭ 147 (-32.57%)
Mutual labels:  codable
Datastack
100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer
Stars: ✭ 212 (-2.75%)
Mutual labels:  coredata
Jsonlab
JSONLab: a native JSON/UBJSON/MassagePack encoder/decoder for MATLAB/Octave
Stars: ✭ 202 (-7.34%)
Mutual labels:  messagepack
Coredatabestpractices
Best Practices in Core Data explained within a demo application
Stars: ✭ 171 (-21.56%)
Mutual labels:  coredata
Clean Architecture Swiftui
SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.
Stars: ✭ 2,925 (+1241.74%)
Mutual labels:  coredata
Core Data Editor
Core Data Editor lets you easily view, edit and analyze applications‘ data. Core Data Editor is compatible with Mac and iOS applications and supports XML, SQLite and binary stores, visualizes all relationships and is able to edit the data and generate Objective-C code for the data model.
Stars: ✭ 2,106 (+866.06%)
Mutual labels:  coredata
Upcomingmovies
Movies app written in Swift 5 using the TMDb API and demonstrating Clean Architecture, Dependency Injection, MVVM and Coordinators.
Stars: ✭ 160 (-26.61%)
Mutual labels:  coredata
Codable Diy Kit
A template for creating your own Swift Codable encoders and decoders
Stars: ✭ 207 (-5.05%)
Mutual labels:  codable
Justpersist
JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box. It also allows you to migrate to any other persistence framework with minimal effort.
Stars: ✭ 157 (-27.98%)
Mutual labels:  coredata
React Native Default Preference
Use SharedPreference (Android) and UserDefaults (iOS) with React Native over a unified interface
Stars: ✭ 170 (-22.02%)
Mutual labels:  userdefaults
Codablewrappers
A Collection of PropertyWrappers to make custom Serialization of Swift Codable Types easy
Stars: ✭ 197 (-9.63%)
Mutual labels:  codable
Regularexpressiondecoder
A decoder that constructs objects from regular expression matches.
Stars: ✭ 169 (-22.48%)
Mutual labels:  codable
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].

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].