Skip to content

Instantly share code, notes, and snippets.

@wildthink
Created April 18, 2018 02:02
Show Gist options
  • Save wildthink/7e084bac2492c3e42c1072bdf20bb87c to your computer and use it in GitHub Desktop.
Save wildthink/7e084bac2492c3e42c1072bdf20bb87c to your computer and use it in GitHub Desktop.
Neatly wrap object->plist->object functions
import Foundation
func reify<T:Codable>(type: T.Type, _ json: String) -> T? {
let data = json.data(using: .utf16)
let nob = try? JSONDecoder().decode(T.self, from: data!)
return nob
}
func plist<T:Codable>(_ nob: T) -> Any? {
guard let data = try? JSONEncoder().encode(nob) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: [.mutableContainers, .allowFragments])
}
// Example
struct Person: Codable {
var name = "fred"
var age = 23
}
func testPlist() {
let nob = Person()
var pl = plist(nob) as! [String:Any]
Swift.print(pl)
pl["name"] = "joe"
Swift.print(pl) // ["name": fred, "age": 23]
let bob: Person? = reify(type: Person.self, pl.debugDescription)
Swift.print (bob) // ["name": "joe", "age": 23]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment