I am reading dictionary from a plist file and based on the object type I want to construct and initialize objects of appropriate class. Here is my code:
enum ItemType:String {
case type1, type2, type3, type4,...
}
class SuperItem {
var type:ItemType
init?(_ dictionary:[String:Any]) {
if let typeString = dictionary["type"] as? String, let type = ItemType(typeString) {
self.type = type
} else {
return nil
}
}
...
}
class TypeOneItem: SuperItem {
override var type:ItemType = .type1
...
}
class TypeTwoItem: SuperItem {
override var type:ItemType = .type2
...
}
My problem is when I am initialising with dictionary in SuperItem, if type == type1 it should initialize and return object of type TypeOneItem instead of SuperItem, and so on for other types. Is there any way to achieve this in Swift?