Created
September 6, 2014 05:20
-
-
Save nek023/622c3c304c5e631e5bb5 to your computer and use it in GitHub Desktop.
Swift-JSONを自分なりに書いてみる練習 (書きかけ)
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 Cocoa | |
let JSONErrorDomain: String = "JSONErrorDomain" | |
enum JSONErrorCode: Int { | |
case InvalidData = 0 | |
} | |
@objc class JSON: NSObject { | |
private(set) var object: AnyObject? | |
@objc(isValid) var valid: Bool { | |
get { | |
if object != nil { | |
return NSJSONSerialization.isValidJSONObject(object!) | |
} else { | |
return false | |
} | |
} | |
} | |
init(object: AnyObject?) { | |
super.init() | |
self.object = object | |
} | |
convenience init(data: NSData, error: NSErrorPointer) { | |
self.init(object: NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error)) | |
} | |
convenience init(string: String, error: NSErrorPointer) { | |
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { | |
self.init(object: NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error)) | |
} else { | |
self.init(object: nil) | |
error.memory = NSError( | |
domain: JSONErrorDomain, | |
code: JSONErrorCode.InvalidData.toRaw(), | |
userInfo: nil | |
) | |
} | |
} | |
} | |
extension JSON { | |
override var description: String { | |
if object != nil { | |
return "\(object!)" | |
} else { | |
return "nil" | |
} | |
} | |
} | |
extension JSON { | |
subscript(key: NSCopying) -> JSON { | |
if let dictionary = object as? NSDictionary { | |
if let object: AnyObject = dictionary[key] { | |
return JSON(object: object) | |
} | |
} | |
return JSON(object: nil) | |
} | |
subscript(index: UInt) -> JSON { | |
if let array = object as? NSArray { | |
return JSON(object: array[Int(index)]) | |
} | |
return JSON(object: nil) | |
} | |
} | |
extension JSON { | |
var isNil: Bool { return object == nil } | |
var asArray: NSArray { return object as NSArray } | |
var asDictionary: NSDictionary { return object as NSDictionary } | |
var asString: String { return object as String } | |
var asInt: Int { return object as Int } | |
var asBool: Bool { return object as Bool } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment