Created
March 24, 2023 03:12
-
-
Save jodoherty/5434722f7dfadafc6b36be9d943d1f4c to your computer and use it in GitHub Desktop.
Encoding/decoding struct as JSON embedded in a binary plist
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
import ArgumentParser | |
import Foundation | |
struct MyStruct: Codable { | |
var id: Int = 0 | |
var name: String = "" | |
var port: Int? | |
} | |
let myStructKey = "myStructs" | |
@main | |
struct NSKeyedTester: ParsableCommand { | |
static var configuration = CommandConfiguration( | |
abstract: "NSKeyedArchiver tests", | |
subcommands: [Read.self, Write.self], | |
defaultSubcommand: Write.self) | |
struct Options: ParsableArguments { | |
@Argument var filename: String = "./hello.plist" | |
} | |
struct Read: ParsableCommand { | |
@OptionGroup var options: Options | |
mutating func run() throws { | |
let localURL = URL(fileURLWithPath: options.filename) | |
let data = try Data(contentsOf: localURL) | |
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data) | |
let json = unarchiver.decodeDecodable(String.self, forKey: myStructKey)! | |
let decoder = JSONDecoder() | |
let decoded = try decoder.decode(Array<MyStruct>.self, from: json.data(using: .utf8)!) | |
print(decoded) | |
} | |
} | |
struct Write: ParsableCommand { | |
@OptionGroup var options: Options | |
mutating func run() throws { | |
let localURL = URL(fileURLWithPath: options.filename) | |
let encoder = JSONEncoder() | |
let data = try encoder.encode([ | |
MyStruct(id: 1, name: "Test"), | |
MyStruct(id: 100, name: "Hello"), | |
MyStruct(id: 100, name: "With port", port: 100), | |
]) | |
let json = String(data: data, encoding: .utf8)! | |
let archiver = NSKeyedArchiver(requiringSecureCoding: true) | |
archiver.outputFormat = .binary | |
try archiver.encodeEncodable(json, forKey: myStructKey) | |
archiver.finishEncoding() | |
try archiver.encodedData.write(to: localURL) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment