Skip to content

Instantly share code, notes, and snippets.

@daveyostcom
Created February 12, 2018 00:42
Show Gist options
  • Save daveyostcom/9faa5add510bb223499cee72f9c9cff8 to your computer and use it in GitHub Desktop.
Save daveyostcom/9faa5add510bb223499cee72f9c9cff8 to your computer and use it in GitHub Desktop.
Example code in Swift 4.1 for JSON using the Codable protocol
#!/usr/bin/swift
// swift-4.1-Codable-JSON.swift
//
// Example code in Swift 4.1 for JSON using the Codable protocol
import Foundation
let encoder = JSONEncoder()
let decoder = JSONDecoder()
struct Person : Codable {
var name = "Taylor"
}
let peopleOut = [Person()]
print("Original: \(peopleOut)")
guard let dataOut = try? encoder.encode(peopleOut) else {
fatalError("Failed to encode the object.")
}
guard let stringEncoded = String(data: dataOut, encoding: .utf8) else {
fatalError("Failed to convert the data to a String.")
}
print("Encoded: \(stringEncoded)")
guard let dataIn = stringEncoded.data(using: .utf8, allowLossyConversion: false) else {
fatalError("Failed to convert the encoded string to data.")
}
guard let peopleIn = try? decoder.decode([Person].self, from: dataIn) else {
fatalError("Failed to decode the data.")
}
print("Decoded: \(peopleIn))")
// after Paul Hudson's
// What’s new in Swift 4.1
// https://www.hackingwithswift.com/articles/50/whats-new-in-swift-4-1
// 2018-02-11 Output with the Xcode 9.3 beta2 swift toolchain
// Original: [main.Person(name: "Taylor")]
// Encoded: [{"name":"Taylor"}]
// Decoded: [main.Person(name: "Taylor")])
// The trailing ) was actually in the output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment