jeudi 5 février 2015

Creating a superclass which will enable custom initialization from Dictionary for its subclasses

What I have done:


I have several model classes, which have a variable number of attributes each. For example:



class A{
var a1 : String
var a2 : Int

init(){...}
}

class B{
var b1 : String
var b2 : Int
var b3 : AnyObject

init(){...}
}


and so on. To initialize these classes from a Dictionary, I made a custom initializer with a Dictionary parameter and set each of the attributes like this



public class A{
var a1 : String
var a2 : Int

public init(d : Dictionary<String,AnyObject>){
if let value = d["a1"] as? String {
a1 = value
}else{
a1 = ""
}

if let value = d["a2"] as? Int {
a2 = value
}else{
a2 = 0
}
}
}


So, basically I am able to initialze the class A like so:



var objectOfClassA : A = A(d:["a1":"str", "a2":10])


If the Dictionary does not have a proper value corresponding to the key attribute of the class, it will just assign a default value to that attribute.




The problem:


In this implementation, my problem is that I will have to write the init method for each of the model classes that I want to create. My goal is to avoid writing the init method for every model class.




What I want to achieve:


Instead of writing the init method for each model class , I want to make a super class Model which will give a Dictionary init method like this to all its subclasses. So my Class A will look like this:



class A : Model{
var a1 : String
var a2 : Int
}


and still should initialize like before from a Dictionary. Is this possible in Swift?


I tried to use Swift's reflection function to check the properties of the object being initialized, but I was not able to set the property from the dictionary. I guess the properties which can be seen by reflect(self)[1] are read-only. Please advise me on how to implement this type of functionality.


Aucun commentaire:

Enregistrer un commentaire