首页 > 解决方案 > PersonalityQuiz guided app in swift fundamentals

问题描述

I've got problem with some additional challenges. I need to filter an array of type Question by some property and then pass it into next View Controller via segue. I've done this:

  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)
}

Filtration works but it doesn't pass value to next View Controller. I declared variable in QuestionViewControler like that

var correctQuestions: [Question] = []

But when I need to access it I get error "Index out of range". So I figured that its empty..

Segues been made from buttons to VC

标签: iosarraysswiftsegue

解决方案


Ok. I've got it. The NavigationController was the problem here. Added into function push through NC and it worked ;) so closed I think

   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
        }
    }
}

推荐阅读