vinhnx / swift_learning_notes

Notes from learning Swift
https://github.com/vinhnx/swift_learning_notes/issues
0 stars 0 forks source link

"this is how I parse JSON in Swift" #1

Open vinhnx opened 8 years ago

vinhnx commented 8 years ago

http://ctarda.com/2016/06/this-is-how-i-parse-json-in-swift/

struct BlogPost {
    let id: Int
    let text: String    
    let thumbURL: NSURL
    let linkURL: NSURL
}

extension BlogPost {
    private struct Keys {
        static let id = "id"
        static let text = "text"
        static let thumbURL = "thumb_url"
        static let linkURL = "link_url"
    }

    init?(JSON: AnyObject) {
        guard let id = JSON[Keys.id] as? Int,
            let text = JSON[Keys.text] as? String,
            let jsonThumbURL = JSON[Keys.thumbURL] as? String,
            let jsonLinkURL = JSON[Keys.linkURL] as? String,
            let thumbURL = NSURL(string: jsonThumbURL),
            let linkURL = NSURL(string: jsonLinkURL) else {
                return nil
        }

        self.id = id
        self.text = text
        self.thumbURL = thumbURL
        self.linkURL = linkURL
    }

}