Swift:创建具有不同自定义类型的数组

时间:2016-01-16 05:30:27

标签: ios arrays swift

我正在制作注册表单应用。这使用户可以在UITableView中创建问题并显示创建的问题。用户可以创建两种类型的问题,文本输入(使用文本字段)和多项选择(使用分段控制)。这是我为实现这一目标而创建的课程。

class Question {
var Label: String
var required: Int

// create question
init (Label: String, required: Int) {
    self.Label = Label
    self.required = required

    if (self.required == 0) {
        self.Label = self.Label + " *"
    }
}
}

class textInput: Question {
var placeHolder: String

init (placeHolder: String, Label: String, required: Int) {
    self.placeHolder = placeHolder
    super.init(Label: Label, required: required)
}
}

class multiChoice: Question {
var answers: [String]

init(answers: [String], Label: String, required: Int) {
    self.answers = answers
    super.init(Label: Label, required: required)
}
}

我需要使用textInput或multiChoice类型填充数组,这些类型将显示在UITableView中。在C ++中,您可以使用模板来完成此任意类型的问题。有没有办法在Swift中做到这一点,如果是这样,我可以得到如何使用这些类的指针?

2 个答案:

答案 0 :(得分:1)

首先关闭。按如下方式更改您的Question课程:

var required: Bool

init (Label: String, required: Bool) {
    self.Label = Label
    self.required = required

    if self.required {
        self.Label = self.Label + " *"
    }
}

接下来,您可以使用[Question]类型的数组来实现您的目标。然后,您可以使用guardif let结构基于该类执行特定操作。

答案 1 :(得分:1)

实现您想要的非常干净且类型安全的一种方法是创建一个enum,其中包含您将使用的不同类型的关联值。然后,您可以创建一个enum值数组,并使用switch解包它们以获得您想要的值。

class QuestionBase {
    var label: String
    var required: Bool

    // create question
    init (label: String, required: Bool) {
        self.label = label
        self.required = required

        if required {
            self.label = self.label + " *"
        }
    }
}

class TextInputQuestion: QuestionBase {
    var placeHolder: String

    init (placeHolder: String, label: String, required: Bool) {
        self.placeHolder = placeHolder
        super.init(label: label, required: required)
    }
}

class MultiChoiceQuestion: QuestionBase {
    var answers: [String]

    init(answers: [String], label: String, required: Bool) {
        self.answers = answers
        super.init(label: label, required: required)
    }
}

enum Question {
    case TextInput(TextInputQuestion)
    case MultiChoice(MultiChoiceQuestion)
}

let q1 = TextInputQuestion(placeHolder: "placeholder", label: "q1", required: true)
let q2 = MultiChoiceQuestion(answers: ["answer1", "answer2"], label: "q2", required: false)

let questions: [Question] = [.TextInput(q1), .MultiChoice(q2)]

for question in questions {
    switch question {
    case .TextInput(let question):
        print(question.placeHolder)
    case .MultiChoice(let question):
        print(question.answers)
    }
}

enum这种方式非常强大。该数组都是一种类型:Question。关联值可以是任何类型。您可以拥有TrueFalse case,甚至是Essay case

我重写了你的大部分代码 - 它违反了许多Swift风格的指导方针,因此很难阅读。类型名称(如class名称)应全部为LikeThis(以大写字母开头),而属性应全部位于camelCase(以小写字母开头)。我重新命名了一些类型,以便更清楚地说明意图是什么。您可以接受这些更改或保留这些更改。

相关问题