Skip to content

Instantly share code, notes, and snippets.

@benrigas
Last active November 2, 2017 14:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benrigas/0cd3639d1ebf77033bba to your computer and use it in GitHub Desktop.
Save benrigas/0cd3639d1ebf77033bba to your computer and use it in GitHub Desktop.
Swift Playground for initializing objects from Dictionary/JSON
// 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!")
}
@closer27
Copy link

closer27 commented Nov 2, 2017

I forked and rewrote this in Swift4
check out here https://gist.github.com/closer27/59d481d51eb5bc2fe3e24a21d9f3f8e4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment