Skip to content

Instantly share code, notes, and snippets.

@zhigang1992
Created December 18, 2016 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhigang1992/de04fdc839287f363dd22bc58deacd1c to your computer and use it in GitHub Desktop.
Save zhigang1992/de04fdc839287f363dd22bc58deacd1c to your computer and use it in GitHub Desktop.
SwiftyJSON performant alternative
struct JSON {
var value: Optional<NSObject>
subscript(index: Int) -> JSON {
get {
return JSON(value: value.flatMap({ value in
return (value as? NSArray).flatMap({
if $0.count > index && index >= 0 {
return $0[index] as? NSObject
}
return nil
})
}))
}
set {
let newValueToSet = newValue.value ?? NSNull()
guard let array = self.value as? NSArray else {
self.value = NSMutableArray(object: newValueToSet)
return
}
let mutableArray: NSMutableArray
if let array = array as? NSMutableArray {
mutableArray = array
} else {
mutableArray = array.mutableCopy() as! NSMutableArray
}
guard (mutableArray.count > index && index >= 0) else { return }
mutableArray.replaceObjectAtIndex(index, withObject: newValueToSet)
self.value = mutableArray
}
}
subscript(key: String) -> JSON {
get {
return JSON(value: value.flatMap({ value in
return (value as? NSDictionary).flatMap({$0[key] as? NSObject})
}))
}
set {
let newValueToSet = newValue.value ?? NSNull()
guard let dictionary = self.value as? NSDictionary else {
self.value = NSMutableDictionary(object: newValueToSet, forKey: key as NSString)
return
}
let mutableDictionary: NSMutableDictionary
if let dictionary = dictionary as? NSMutableDictionary {
mutableDictionary = dictionary
} else {
mutableDictionary = dictionary.mutableCopy() as! NSMutableDictionary
}
mutableDictionary.setValue(newValueToSet, forKeyPath: key as String)
self.value = mutableDictionary
}
}
var int: Int? {
get {
return self.value as? Int
}
set {
self.value = newValue.flatMap({ $0 as NSObject})
}
}
var float: Float? {
get {
return self.value as? Float
}
set {
self.value = newValue.flatMap({ $0 as NSObject })
}
}
var string: String? {
get {
return self.value as? String
}
set {
self.value = newValue.flatMap({ $0 as NSObject })
}
}
var bool: Bool? {
get {
return self.value as? Bool
}
set {
self.value = newValue.flatMap({ $0 as NSObject })
}
}
var array: Array<JSON>? {
return (self.value as? NSArray).map({ array in
array.map({JSON(value: $0 as? NSObject)})
})
}
var dictionary: Array<(String, JSON)>? {
return (self.value as? NSDictionary).map({ dictionary in
dictionary.flatMap({ key, value in
guard let key = key as? String else { return nil }
return (key, JSON(value: value as? NSObject))
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment