Skip to content

Instantly share code, notes, and snippets.

@NeoTeo
Created November 9, 2015 09:00
Show Gist options
  • Select an option

  • Save NeoTeo/51314a76e2ceb2d27cfb to your computer and use it in GitHub Desktop.

Select an option

Save NeoTeo/51314a76e2ceb2d27cfb to your computer and use it in GitHub Desktop.
For type classifying JSON
/// Utilities for (eventually) dealing with
/// To be able to map a dictionary we extend it (from thoughtbot/Argo project)
// pure merge for Dictionaries
func + <T, U>(var lhs: [T: U], rhs: [T: U]) -> [T: U] {
for (key, val) in rhs {
lhs[key] = val /// Potential loss: Same key will lose existing lhs value.
}
return lhs
}
extension Dictionary {
func map<T>(f: Value -> T) -> [Key: T] {
return self.reduce([:]) { $0 + [$1.0: f($1.1)] }
}
}
/// Move these to own file
public enum JsonValue {
case Object([Swift.String : JsonValue])
case Array([JsonValue])
case String(Swift.String)
case Number(NSNumber)
case Null
}
public extension JsonValue {
static func parse(json: AnyObject) -> JsonValue {
switch json {
case let value as [AnyObject]: return .Array(value.map(parse))
case let value as [Swift.String : AnyObject]: return .Object(value.map(parse))
case let value as Swift.String: return .String(value)
case let value as NSNumber: return .Number(value)
default: return .Null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment