Created
February 26, 2019 18:23
-
-
Save ElonPark/61242b6bc863888e476f5f4ff481b7c8 to your computer and use it in GitHub Desktop.
Realm, ObjectMapper 사용시 JSON Array를 Realm Object List로 변경하기 위해 사용한다.
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 RealmSwift | |
import ObjectMapper | |
class ArrayTransform<T: RealmSwift.Object>: TransformType where T: Mappable { | |
typealias Object = List<T> | |
typealias JSON = Array<AnyObject> | |
/** | |
- Parameter value: JSON Value | |
- Returns: if value is `nil` or not Array will be return empty List<T> | |
*/ | |
func transformFromJSON(_ value: Any?) -> Object? { | |
let result = Object() | |
guard let _value = value, | |
let objectArray = _value as? Array<AnyObject> else { return result } | |
let mapper = Mapper<T>() | |
for object in objectArray { | |
//if model is `nil` continue to next object | |
guard let model = mapper.map(JSONObject: object) else { | |
continue | |
} | |
result.append(model) | |
} | |
return result | |
} | |
/** | |
- Parameter value: RealmSwift Object | |
- Returns: if value is `nil` or empty will be return empty Array<AnyObject> | |
*/ | |
func transformToJSON(_ value: Object?) -> JSON? { | |
var result = JSON() | |
guard let _value = value, _value.count > 0 else { return result } | |
result = _value.map { $0 } | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ObjectMapper+Realm에 더 깔끔한 코드가 존재함
ListTransform