Last active
November 2, 2017 14:51
-
-
Save benrigas/0cd3639d1ebf77033bba to your computer and use it in GitHub Desktop.
Swift Playground for initializing objects from Dictionary/JSON
This file contains 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
// Playground - noun: a place where people can play | |
import Cocoa | |
extension String { | |
func dictionaryFromJSON () -> Dictionary<String, AnyObject>? { | |
if let dict = NSJSONSerialization.JSONObjectWithData(self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true), | |
options: .AllowFragments, | |
error: nil) as? Dictionary<String,AnyObject> | |
{ | |
return dict | |
} | |
return nil | |
} | |
} | |
class Person { | |
var firstName:String? | |
var lastName:String? | |
var id:Int? | |
convenience init(attributes:Dictionary<String, AnyObject>) { | |
self.init() | |
for (key, value : AnyObject) in attributes { | |
switch key { | |
case "firstName": | |
self.firstName = value as? String | |
case "lastName": | |
self.lastName = value as? String | |
case "id": | |
self.id = value as? Int | |
default: | |
break; | |
} | |
} | |
} | |
} | |
var json : String = "{\"firstName\":\"Bob\",\"lastName\":\"Parr\", \"id\": 113}" | |
if let patientAttributes = json.dictionaryFromJSON() { | |
var person = Person(attributes: patientAttributes) | |
println("Sweet! \(person.firstName) \(person.lastName)") | |
} | |
else { | |
println("Uh oh!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I forked and rewrote this in Swift4
check out here https://gist.github.com/closer27/59d481d51eb5bc2fe3e24a21d9f3f8e4