Last active
April 7, 2017 03:23
-
-
Save cmc5788/6b759850061291058f73f08d79ef43ce to your computer and use it in GitHub Desktop.
Swift JSON / Rx utils
This file contains hidden or 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 RxSwift | |
public protocol StringProtocol {} | |
extension String : StringProtocol {} | |
public typealias JSON = [String : AnyObject] | |
extension ObservableType where Self.E == Any? { | |
public func mapToJSON() -> RxSwift.Observable<JSON> { | |
return self.map { $0 as! JSON } | |
} | |
} | |
extension Dictionary where Key : StringProtocol, Value : AnyObject { | |
public func val<T>(_ type : T.Type, _ path : String, _ converter : ((AnyObject) -> T?)? = nil) -> T? { | |
let components = path.components(separatedBy: ".") | |
if components.isEmpty { return nil } | |
let selfDict = (self as AnyObject) as? JSON | |
if components.count == 1 { | |
let raw : AnyObject? = selfDict?[components[0]] | |
if raw == nil || converter == nil { return raw as? T } | |
return converter!(raw!) | |
} | |
let nextDict = selfDict?[components[0]] as? JSON | |
return nextDict?.val(type, components | |
.suffix(from: 1) | |
.joined(separator: ".")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
well my formatting got all screwed up, but you can use guard statements instead of nil checking.