我正在制作注册表单应用程序。这让用户可以创建问题并在UITableView中显示创建的问题。用户可以创建两种类型的问题,文本输入(使用文本框)和多项选择(使用分段控件)。这是我为创造这个目的而创建的课程。Swift:使用不同的自定义类型创建数组
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中做到这一点,如果可以的话,我可以指出如何使用这些类来做到这一点?
这是行不通的。可以说我有以下几点。 questionsArray:[问题]。比方说,我遍历数组,并得到一个textInput元素。我不能在没有得到错误的情况下调用以下语句,questionsArray [i] .placeholder。 Question基类无权访问“占位符”。这就是为什么我需要一个可以容纳多种自定义类型的数组。 – Malexc
'if let question = questionsArray [i] as? textInput {print(question.placeholder)}' – lukasbalaz7