Skip to content
Dan Kogai edited this page Jul 21, 2014 · 1 revision

Discussion

The first approach to JSON from Swift was directly using what NSJSONSerialization has to offer. Your code would like this:

exerpt from [SwiftyJSON]'s README

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let statusesArray = jsonObject as? NSArray{
    if let aStatus = statusesArray[0] as? NSDictionary{
        if let user = aStatus["user"] as? NSDictionary{
            if let userName = user["name"] as? NSDictionary{
                //Finally We Got The Name

            }
        }
    }
}

or this:

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
  //What A disaster above
}

Then Swifty JSON comes along and changed everything.

let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //Now you got your value
}

Handsome, isn't it. And SwiftyJSON's beauty is not skin deep. Swift's enum rocks!

Or does it?

Swift offers three diffrent flavors of objects: struct, enum and class. They can all have instance properties and type properties. They are all extensible via extension. They are all generics-aware. Then what's the point?

Some thing must be copied by value and that's what struct is for. In swifts primitives are struct that happens to fit in the register. So is enum, which is really a union in disguise. And as with C and friends enums are also copied by value.

Then what happend to copy-by-reference types? Yes, class!. Good old-fasioned OOP is there to stay. In addition to efficiency, Swift's class offers some thing the rest of two do not:

Inheritance!

In Swift, only class is inheritable and that matters in a case like this. Different schema for different JSON trees. You can add methods to enum-based JSONValue but the change is global. It's all or nothing. I wanted something customizable for each JSON endpoint. This piece of code was thus born.

Clone this wiki locally