-
-
Save closer27/59d481d51eb5bc2fe3e24a21d9f3f8e4 to your computer and use it in GitHub Desktop.
Swift4 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>? { | |
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