swift 基础知识中的性格测验指导应用程序

PersonalityQuiz guided app in swift fundamentals

我遇到了一些额外的挑战。我需要通过一些 属性 过滤类型问题的数组,然后通过 segue 将其传递到下一个视图控制器。我已经这样做了:

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let sender = sender as? UIButton else {return}
    if sender == quiz3Button {
        let vc = segue.destination as? QuestionViewController
        vc?.correctQuestions = questions.filter { question in
        return question.quiz == .animals
        }
    } else if sender == quiz4Button {
        let vc = segue.destination as? QuestionViewController
        vc?.correctQuestions = questions.filter { question in
        return question.quiz == .cars
        }
    }
}

@IBAction func quiz3ButtonTapped(_ sender: UIButton) {
    performSegue(withIdentifier: "animals", sender: sender)
}

@IBAction func quiz4Button(_ sender: UIButton) {
    performSegue(withIdentifier: "cars", sender: sender)
}

过滤有效,但它不会将值传递给下一个视图控制器。我像那样在 QuestionViewControler 中声明了变量

var correctQuestions: [Question] = []

但是当我需要访问它时,出现错误“索引超出范围”。所以我认为它是空的..

已从按钮转至 VC

好的。我懂了。 NavigationController 是这里的问题所在。通过 NC 添加到功能推送中并且它起作用了;)我认为如此关闭

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let sender = sender as? UIButton else {return}
    if sender == quiz3Button {
        let destinationViewController = segue.destination as? UINavigationController
        let questionViewController = destinationViewController?.viewControllers.first as! QuestionViewController
        questionViewController.correctQuestions = questions.filter { questions in
        return questions.quiz == .animals
        }
    } else if sender == quiz4Button {
        let destinationViewController = segue.destination as? UINavigationController
        let questionViewController = destinationViewController?.viewControllers.first as! QuestionViewController
        questionViewController.correctQuestions = questions.filter { questions in
        return questions.quiz == .cars
        }
    }
}