Created
April 18, 2018 02:02
-
-
Save wildthink/7e084bac2492c3e42c1072bdf20bb87c to your computer and use it in GitHub Desktop.
Neatly wrap object->plist->object functions
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 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