Skip to content

Instantly share code, notes, and snippets.

@cmc5788
Last active April 7, 2017 03:23
Show Gist options
  • Save cmc5788/6b759850061291058f73f08d79ef43ce to your computer and use it in GitHub Desktop.
Save cmc5788/6b759850061291058f73f08d79ef43ce to your computer and use it in GitHub Desktop.
Swift JSON / Rx utils
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: "."))
}
}
@andrewwells
Copy link

andrewwells commented Apr 7, 2017

well my formatting got all screwed up, but you can use guard statements instead of nil checking.

guard let raw =  selfDict?[components[0]], let converter = converter else { return raw as? T }
return converter(raw)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment