Created
August 3, 2020 15:46
-
-
Save ha1f/4b8afd18756e71d7670a0288a4697fc4 to your computer and use it in GitHub Desktop.
This file contains 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 RealmSwift | |
private extension Object { | |
/// 再帰的にDictionary型に変換する | |
func asDictionary() -> [String: Any] { | |
return objectSchema.properties | |
.reduce(into: [String: Any](), { (dictionary, property) in | |
let value = self[property.name] | |
dictionary[property.name] = _serializableValue(value) | |
}) | |
} | |
} | |
/// Realmのオブジェクトから普通のオブジェクトに変換する | |
protocol SerializableValueConvertible { | |
func asSerializableValue() -> Any | |
} | |
extension List: SerializableValueConvertible { | |
func asSerializableValue() -> Any { | |
return Array(map(_serializableValue)) as Any | |
} | |
} | |
extension RealmOptional: SerializableValueConvertible { | |
func asSerializableValue() -> Any { | |
return value ?? NSNull() | |
} | |
} | |
extension Object: SerializableValueConvertible { | |
func asSerializableValue() -> Any { | |
asDictionary() | |
} | |
} | |
private func _serializableValue(_ value: Any?) -> Any { | |
guard let value = value else { | |
return NSNull() as Any | |
} | |
if let convertible = value as? SerializableValueConvertible { | |
return convertible.asSerializableValue() | |
} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment