swift - 在不同场景中声明类变量

标签 swift class

我对 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/

相关文章:

ios - SKPaymentTransactionObserver 的 updatedTransactions 委托(delegate)方法中什么时候设置交易状态恢复?

iOS 多线程 - NSURLSession 和 UI 更新

javascript - 如何让 getElementsByClassName 定位所有标记元素 - 有更好的选择吗?

c++ - 使用 map 容器的字母频率

javascript - 引用存储在另一个类的数组中的类实例

java - 如何解决StackOverFlowError?

ios - 重用单元格时 CollectionView 的奇怪行为

ios - 苹果 swift : how to get current seconds in 1/100 or 1/1000?

swift - Swift 中的定向碰撞检测

javascript - 用掩码更改类名? (查询)