Skip to content

Instantly share code, notes, and snippets.

@closer27
Forked from benrigas/Swift JSON Playground
Last active November 2, 2017 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save closer27/59d481d51eb5bc2fe3e24a21d9f3f8e4 to your computer and use it in GitHub Desktop.
Save closer27/59d481d51eb5bc2fe3e24a21d9f3f8e4 to your computer and use it in GitHub Desktop.
Swift4 Playground for initializing objects from Dictionary/JSON
// Playground - noun: a place where people can play
import Cocoa
extension String {
func dictionaryFromJSON () -> Dictionary<String, AnyObject>? {
do {
if let data = self.data(using: .utf8), let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
return dict
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
return nil
}
}
class Person {
var firstName:String?
var lastName:String?
var id:Int?
convenience init(attributes:Dictionary<String, AnyObject>) {
self.init()
for (key, value) 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)
print("Sweet! \(person.firstName) \(person.lastName)")
}
else {
print("Uh oh!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment