Skip to content

Instantly share code, notes, and snippets.

@HocTran
Created March 25, 2016 09:19
Show Gist options
  • Save HocTran/8a502fc145c71a3191d3 to your computer and use it in GitHub Desktop.
Save HocTran/8a502fc145c71a3191d3 to your computer and use it in GitHub Desktop.
JSON array to Realm's List type with ObjectMapper
import Foundation
import ObjectMapper
import RealmSwift
class ListTransform<T:RealmSwift.Object where T:Mappable> : TransformType {
typealias Object = List<T>
typealias JSON = [AnyObject]
let mapper = Mapper<T>()
func transformFromJSON(value: AnyObject?) -> Object? {
var results = List<T>()
if let value = value as? [AnyObject] {
for json in value {
if let obj = mapper.map(json) {
results.append(obj)
}
}
}
return results
}
func transformToJSON(value: Object?) -> JSON? {
var results = [AnyObject]()
if let value = value {
for obj in value {
let json = mapper.toJSON(obj)
results.append(json)
}
}
return results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment