Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Last active November 5, 2015 15:38
Show Gist options
  • Save odrobnik/56ed4b90de34933a974c to your computer and use it in GitHub Desktop.
Save odrobnik/56ed4b90de34933a974c to your computer and use it in GitHub Desktop.
Trying to dynamically init the correct class based on a string
class Entity
{
var objectID: String?
var createdAt: NSDate?
var updatedAt: NSDate?
var avatarURL: NSURL?
var wallpaperURL: NSURL?
required init()
{
}
required init(dictionary: Dictionary<String, AnyObject>)
{
if let objectID = dictionary["objectId"] as? String
{
self.objectID = objectID
}
if let createdAt = dictionary["createdAt"] as? String
{
self.createdAt = NSDate.dateFromJSONDateString(createdAt)
}
if let updatedAt = dictionary["updatedAt"] as? String
{
self.updatedAt = NSDate.dateFromJSONDateString(updatedAt)
}
if let wallpaper = dictionary["avatar"] as? Dictionary<String, String>,
urlString = wallpaper["url"],
URL = NSURL(string: urlString)
{
self.avatarURL = URL
}
if let wallpaper = dictionary["wallpaper"] as? Dictionary<String, String>,
urlString = wallpaper["url"],
URL = NSURL(string: urlString)
{
self.wallpaperURL = URL
}
}
func dictionaryRepresentation() -> Dictionary<String, String>
{
return Dictionary<String,String>()
}
}
// Organization is also a subclass that has additional properties and the same init(dictionary:...)
This works:
func typeForName(name: String) -> Entity.Type
{
if name == "Organization"
{
return Organization.self
}
return Entity.self
}
let expectedClass = self.typeForName("Organization")
let result = expectedClass.init(dictionary: resultsDictionary);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment