类型“ UIViewController”的值没有成员“ indexOf”

she*_*ric 1 indexing swift

已针对新问题进行了编辑:类型为“ QuestionController”的实例成员“ questionsList”不能在嵌套类型为“ QuestionController.QuestionController”的实例上使用

有人可以解释快速解决方案吗?我仍在学习Swift,所以不太清楚它要我做什么。

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {            
    if let index = navigationController?.viewControllers.indexOf()->() {
        let question = questionsList[index]
        if let count = question.answers?.count {
            return count
         }
    }
    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath as IndexPath) as! AnswerCell

    if let index = navigationController?.viewControllers.indexOf() {
       let question = questionsList[index]
       cell.nameLabel.text = question.answers?[indexPath.row]
    }
Run Code Online (Sandbox Code Playgroud)

新问题:

错误首先出现在第47行:

import UIKit

struct Question {
    var questionString: String?
    var answers: [String]?
    var selectedAnswerIndex: Int?
}

class QuestionController: UITableViewController {

    let cellId = "cellId"
    let headerId = "headerId"

    var questionsList: [Question] = [Question(questionString: "What is your favorite type of food?", answers: ["Sandwiches", "Pizza", "Seafood", "Unagi"], selectedAnswerIndex: nil), Question(questionString: "What do you do for a living?", answers: ["Paleontologist", "Actor", "Chef", "Waitress"], selectedAnswerIndex: nil), Question(questionString: "Were you on a break?", answers: ["Yes", "No"], selectedAnswerIndex: nil)]

    class QuestionController: UITableViewController {

        let cellId = "cellId"
        let headerId = "headerId"

        override func viewDidLoad() {
            super.viewDidLoad()

            navigationItem.title = "Question"

            navigationController?.navigationBar.tintColor = UIColor.white
            navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)

            tableView.register(AnswerCell.self, forCellReuseIdentifier: cellId)
            tableView.register(QuestionHeader.self, forHeaderFooterViewReuseIdentifier: headerId)

            tableView.sectionHeaderHeight = 50
            tableView.tableFooterView = UIView()
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            if let index = navigationController?.viewControllers.index(of: self) {
                let question = questionsList[index]
                if let count = question.answers?.count {
                    return count
Run Code Online (Sandbox Code Playgroud)

Tam*_*gel 7

如果要获取当前视图控制器的索引,则应将其作为输入。另外,indexOffirstIndex(of:)因为斯威夫特5。

let index = navigationController?.viewControllers.firstIndex(of: self)
Run Code Online (Sandbox Code Playgroud)