dimanche 31 janvier 2016

Swift reflection capabilities

Given a constructor such as:

required init (pTableName : String, pRecordKey : String, pStartAtRecord : Int){
    parameters.append(ChildElement(identifier: "pTableName", value: pTableName))
    parameters.append(ChildElement(identifier: "pRecordKey", value: pRecordKey))
    parameters.append(ChildElement(identifier: "pStartAtRecord", value: pStartAtRecord))
}

I want to extract the names of all argument variables such as pTableName, pRecordKey and so forth. Why exactly? First of all, I might have more then 30 different classes having different constructor arguments and passing those into the parameters array. Secondly, all of the constructors have a different signature, but mainly they do the same thing - create ChildElements and append them to the list of parameters - which afterwards constitutes a SOAP request for the web service.

By having the ability of getting the variable names (e.g. pTableName should produce "pTableName" : String), I would like to accomplish the following:

required init (pTableName : String, pRecordKey : String, pStartAtRecord : Int){
    appendToParameters([pTableName, pRecordKey, pStartAtRecord])
} 

which would then for each element of the array produce:

parameters.append(ChildElement(identifier: Reflection.getName(var), value : var))

However, in Swift there is no possibility of getting the variable name using reflection and macros such as the one used in Objective-C:

#define variableName(var) [NSString stringWithFormat:@"%s",#var]

If I try to use the macro via an Objective C method, and then applied in Swift:

-(NSString *)getVarName:(id)var {
    return variableName(var)
}

then of course the return NSString value will be equal to "var".

In general, how can I use reflection in Swift in order to obtain, as in this example the name of a argument variable? So far, I've checked numerous resources, starting from the Apple's documentation onto the runtime API and similar, but unfortunately, none of the pre-defined runtime methods seem to be applicable in Swift.

Any piece of advice?

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire