Last active
April 16, 2016 16:39
-
-
Save wanewang/93b52c081dd2afe43cd7048a1fe0fcbf 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 RxSwift | |
import Genome | |
import PureJsonSerializer | |
enum JsonError: String { | |
case CouldNotParseJSON | |
} | |
extension JsonError: ErrorType { } | |
extension Observable { | |
typealias Dictionary = [String: AnyObject] | |
/// Get given JSONified data, pass back objects | |
func mapToObject<B: MappableObject>(classType: B.Type) -> Observable<B> { | |
return self.map { json in | |
guard let dict = json as? Dictionary else { | |
throw JsonError.CouldNotParseJSON | |
} | |
return try B.newInstance(Json.from(dict)) | |
} | |
} | |
/// Get given JSONified data, pass back objects as an array | |
func mapToObjectArray<B: MappableObject>(classType: B.Type) -> Observable<[B]> { | |
return self.map { json in | |
guard let array = json as? [AnyObject] else { | |
throw JsonError.CouldNotParseJSON | |
} | |
guard let dicts = array as? [Dictionary] else { | |
throw JsonError.CouldNotParseJSON | |
} | |
return dicts.flatMap { json -> B? in | |
do { | |
return try B.newInstance(Json.from(json)) | |
} catch { | |
return nil | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment