Skip to content

Instantly share code, notes, and snippets.

@ingconti
Last active June 19, 2023 04:27
Show Gist options
  • Save ingconti/9b01e6d9e817e80e97024f161d93d480 to your computer and use it in GitHub Desktop.
Save ingconti/9b01e6d9e817e80e97024f161d93d480 to your computer and use it in GitHub Desktop.
real JSON encode / decode for CGRect
import Foundation
import CoreGraphics
// Apple does implement Codable, but is NOT really JSON and fails with arrys of CGRects.
extension CGRect {
func toDict()->Dict{
let d : Dict = [
"origin" : ["x" : self.origin.x, "y" : self.origin.y],
"size" : ["w" : self.size.width, "h" : self.size.height]
//"size" : ["w": self.size.width, "h" : self.size.h],
]
return d
}
static func from(dict: Dict?)->CGRect?{
guard let dict = dict else {
return nil
}
if let originDict = dict["origin"] as? Dict, let sizeDict = dict["size"] as? Dict {
let x = originDict["x"] as? CGFloat
let y = originDict["y"] as? CGFloat
let w = sizeDict["w"] as? CGFloat
let h = sizeDict["h"] as? CGFloat
if let x=x, let y=y, let w=w, let h=h{
let r = CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: w, height: h))
return r
}
}
return nil
}
// put in whatever class / controllor on OSX / iOS You want to experiment it.
// (a dedicated test Unit will be good. but is a Gist...)
static func TestSerialize(){
let IMEIBarCodeRect = CGRect(x: 10, y: 20, width: 100, height: 200)
let IMEIStringRect = CGRect(x: 11, y: 20, width: 100, height: 200)
let rectsDict = [
"IMEIBarCodeRect" : IMEIBarCodeRect.toDict(),
"IMEIStringRect" : IMEIStringRect.toDict(),
]
guard let jsonData : Data = try? JSONSerialization.data(withJSONObject: rectsDict, options: []) else{
return
}
// to see what we produce... print or save.
let s = String(data: jsonData, encoding: .utf8)
///decode:
if let rectsDict = try? JSONSerialization.jsonObject(with: jsonData, options: [] ) as? Dict {
if let r1 = CGRect.from(dict: rectsDict["IMEIBarCodeRect"] as! Dict){
print(r1)
if IMEIBarCodeRect == r1{
print("OK")
}
}
if let r2 = CGRect.from(dict: rectsDict["IMEIStringRect"] as! Dict){
print(r2)
if IMEIStringRect == r2{
print("OK")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment