Skip to content

Instantly share code, notes, and snippets.

@guidomb
Created March 25, 2018 00:14
Show Gist options
  • Save guidomb/91e1beb43cad80352b68f0a320608c46 to your computer and use it in GitHub Desktop.
Save guidomb/91e1beb43cad80352b68f0a320608c46 to your computer and use it in GitHub Desktop.
A generic serialization function in Swift using Mirror API
func serialize(object: Any) -> [String : Any]? {
let mirror = Mirror(reflecting: object)
guard mirror.displayStyle == .struct || mirror.displayStyle == .class else {
return .none
}
var result: [String : Any] = [:]
for case let (label?, value) in mirror.children {
let childMirror = Mirror(reflecting: value)
if let displayStyle = childMirror.displayStyle {
switch displayStyle {
case .`class`:
result[label] = serialize(object: value)
case .collection:
result[label] = Array(childMirror.children.lazy
.map { (_, value) in serialize(object: value) }
.filter { $0 != nil }
.map { $0 as! [String : Any]})
case .dictionary:
result[label] = serialize(object: value)
case .`enum`:
// not supported
break
case .optional:
switch childMirror.children.first {
case let .some((.some("some"), childValue)):
result[label] = serialize(object: childValue) ?? childValue
default:
result[label] = NSNull()
}
break
case .set:
result[label] = Array(childMirror.children.lazy
.map { (_, value) in serialize(object: value) }
.filter { $0 != nil }
.map { $0 as! [String : String]})
case .`struct`:
result[label] = serialize(object: value)
case .tuple:
// not supported
break
}
} else {
result[label] = "\(value)"
}
}
return result
}
let user = User(
email: "guidomb@gmail.com",
password: "asdasd",
friends: [
User(email: "anita@gmail.com", password: "123456"),
User(email: "luciano@gmail.com", password: "asd123456")
]
)
print(serialize(object: user))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment