我对 Swift 还很陌生。我正在创建一个允许用户创建注册表单的应用程序。我有两个文件/场景,FirstViewController 和 SecondViewController。 SecondViewController 允许用户创建问题。 FirstViewController 将在 UITableView 中显示所有创建的问题。在我的 SecondViewController 中,我有一个名为 Question 的类,它基本上可以帮助我创建一个问题,如下所示的上下文。
class Question {
var Label: String
var required: Int
// create question
init (Label: String, required: Int) {
self.Label = Label
self.required = required
}
}
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)
}
}
在 FirstViewController 中,我需要创建一个该类型的数组,以保存 UITableView 中所有问题的运行列表...
var formQuestions: [Question]
显然 FirstViewController 无法访问此自定义对象类型。我的问题是我该如何做到这一点?我可以将整个类复制并粘贴到我的 FirstViewController 中,但这将是糟糕的编程......
感谢您的帮助。
最佳答案
您的 FirstViewController
无法访问 Question
类及其子类,因为它们都是在 SecondViewController
中声明的。这意味着它们是 SecondViewController
本地的,其他地方都无法访问它。您需要做的是将问题类设为全局。
所以现在你的类(class)是这样的:(内容省略)
class SecondViewController: UIViewController {
class Question {
}
class TextInputQuestion: Question {
}
class MultiChoiceQuestion: Question {
}
}
您应该将它们移出SecondViewController
:
class SecondViewController {
}
class Question {
}
class TextInputQuestion: Question {
}
class MultiChoiceQuestion: Question {
}
哦,顺便说一句,我重命名了你的类(class)名称!您应该始终对类使用 PascalCase,并且我认为添加单词 Question
会更能描述它们的含义。
关于swift - 在不同场景中声明类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803399/