-
-
Save slimlime/458cca9a8144733b50c714161a32e195 to your computer and use it in GitHub Desktop.
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 | |
import SceneKit | |
let json = """ | |
{ | |
"position": [2.0, 5.0, 3.0], | |
"rotation": [0.0, 0.73, 0.0, 0.73] | |
} | |
""".data(using: .utf8)! | |
extension SCNVector3: Codable { | |
public init(from decoder: Decoder) throws { | |
var container = try decoder.unkeyedContainer() | |
self.x = try container.decode(CGFloat.self) | |
self.y = try container.decode(CGFloat.self) | |
self.z = try container.decode(CGFloat.self) | |
} | |
public func encode(to encoder: Encoder) throws { | |
var container = encoder.unkeyedContainer() | |
try container.encode(self.x) | |
try container.encode(self.y) | |
try container.encode(self.z) | |
} | |
} | |
extension SCNVector4: Codable { | |
public init(from decoder: Decoder) throws { | |
var container = try decoder.unkeyedContainer() | |
self.x = try container.decode(CGFloat.self) | |
self.y = try container.decode(CGFloat.self) | |
self.z = try container.decode(CGFloat.self) | |
self.w = try container.decode(CGFloat.self) | |
} | |
public func encode(to encoder: Encoder) throws { | |
var container = encoder.unkeyedContainer() | |
try container.encode(self.x) | |
try container.encode(self.y) | |
try container.encode(self.z) | |
try container.encode(self.w) | |
} | |
} | |
struct ModelState: Codable { | |
let position: SCNVector3 | |
let rotation: SCNVector4 | |
} | |
let decoder = JSONDecoder() | |
do { | |
let state = try decoder.decode(ModelState.self, from: json) | |
print(state) | |
} catch { | |
print ("\(error.localizedDescription)") | |
} | |
let encoder = JSONEncoder() | |
let state = ModelState(position: SCNVector3(1, 2, 3), rotation: SCNVector4(0.73, 0, 0, -0.73)) | |
do { | |
let data = try encoder.encode(state) | |
let text = String(data: data, encoding: .utf8)! | |
print(text) | |
} catch { | |
print ("\(error.localizedDescription)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment