1

ResearchKit has ORKOrderedTask a class to add steps like Instruction, Survey, Activity to it. Through class mapping I determine the given response from server comes under which step. And my mapping is as follows

let classMapping = [
"ORKInstructionStep": ORKInstructionStep.self,
"ORKQuestionStep": ORKQuestionStep.self,
"ORKFormStep": ORKFormStep.self,
"ORKFormItem": ORKFormItem.self
]

If I add a question step to ORKOrderedTask. And the question step structure to store data from server is as follows

struct QuestionGroup {
let identifier, title, text : String
let answerFormat: ORKAnswerFormat
init(identifier: String, title: String, text: String, answerFormat: ORKAnswerFormat) {
    self.identifier   = identifier
    self.title = title
    self.text  = text
    self.answerFormat = ORKAnswerFormat()
}
}

And I store the date to the question group structure from server as follows

LIbraryAPI.sharedInstance.questionList.append(QuestionGroup(identifier: row["objectId"]!.string!, 
title: row["title"]!.string!, text: row["text"]!.string!, answerFormat: ORKBooleanAnswerFormat()))

In the above code the answerFormat is hard coded as of now, but can be of any of the answer format in this following enum

enum AnswerFormat: Int {
case ORKScaleAnswerFormat = 0,
ORKContinuousScaleAnswerFormat,
ORKValuePickerAnswerFormat,
ORKImageChoiceAnswerFormat,
ORKTextChoiceAnswerFormat,
`ORKBooleanAnswerFormat`,
ORKNumericAnswerFormat,
ORKTimeOfDayAnswerFormat,
ORKDateAnswerFormat,
ORKTextAnswerFormat,
ORKTimeIntervalAnswerFormat
   }

For each answer format there will be different argument to pass. Following is the final code where I add the question step to ORKOrderedTask.

  if let questionStep  = classMapping["ORKQuestionStep"] as? ORKQuestionStep {
    let tempStep = questionStep.dynamicType
    let group = LIbraryAPI.sharedInstance.questionList
    for eachGroup in group {
        let finalQuestionStep = tempStep(identifier: eachGroup.identifier, title: eachGroup.title, answer: eachGroup.answerFormat)
        steps += [finalQuestionStep]
    }
}

So my problem is the server passes me different kind of answer format for each question. How do I dynamically create the instance of each answer format that comes under AnswerFormat enum? Because ORKBooleanAnswerFormat does not have any arguments, on the other hand ORKTextChoiceAnswerFormat can have an array of strings as an argument and Date answer format must be supplied with max and min date so on and so forth.

So how do I manage all these and bring under one single class or function to make it reusable for all the answer format classes?

j08691
  • 204,283
  • 31
  • 260
  • 272
rootcoder
  • 187
  • 2
  • 13
  • 1
    Have a look at [Josh Smith's *ObjectFactory*](http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/), it might be helpful to your needs. – Ricardo Sanchez-Saez Sep 09 '15 at 11:25

0 Answers0